#!/bin/sh
#
# Copyright (C) 2015, 2017, 2019, 2020, 2022  Etersoft
# Copyright (C) 2015, 2017, 2019, 2020, 2022  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#


# args: appname/appscript
get_play_script()
{
    local playscript="$1"
    is_abs_path "$playscript" || playscript="$psdir/$1.sh"
    echo "$playscript"
}


has_play_script()
{
    local script="$(get_play_script "$1")"
    shift
    [ -f "$script.rpmnew" ] && warning 'There is .rpmnew file ${script}.rpmnew. The play script can be outdated.'
    [ -s "$script" ]
}


__run_script()
{
    local script="$(get_play_script "$1")"
    shift
    has_play_script "$script" || return

    local bashopt=''
    [ -n "$debug" ] && bashopt='-x'

    [ "$PROGDIR" = "/usr/bin" ] && SCPATH="$PATH" || SCPATH="$PROGDIR:$PATH"
    ( unset EPMCURDIR ; export PATH=$SCPATH ; $CMDSHELL $bashopt $script "$@" )
    return
}


# args: script, host arch
__get_app_description()
{
    local arch="$2"
    #__run_script "$1" --description "$arch" 2>/dev/null
    #return
    if grep -q '^SUPPORTEDARCHES=.*\<'"$arch"'\>' "$psdir/$1.sh" || grep -q "^SUPPORTEDARCHES=[\"'][\"']$" "$psdir/$1.sh" || ! grep -q "^SUPPORTEDARCHES=" "$psdir/$1.sh" ; then
        grep -oP "^DESCRIPTION=[\"']*\K[^\"']+" "$psdir/$1.sh" | sed -e 's| *#*$||'
    fi
}


__epm_play_run()
{
    local script="$(get_play_script "$1")"
    shift

    local addopt
    addopt="$dryrun $non_interactive"

    local bashopt=''
    [ -n "$debug" ] && bashopt='-x'
    #info "Running $($script --description 2>/dev/null) ..."
    [ "$PROGDIR" = "/usr/bin" ] && SCPATH="$PATH" || SCPATH="$PROGDIR:$PATH"
    ( export EPM_OPTIONS="$EPM_OPTIONS $addopt" export PATH=$SCPATH ; docmd $CMDSHELL $bashopt $script "$@" )
}


__epm_play_remove()
{
    local prescription
    for prescription in $* ; do
        # run play script
        if has_play_script "$prescription" ; then
            __epm_play_run $prescription --remove
            __remove_installed_app "$prescription"
        else
            psdir=$prsdir
            has_play_script "$prescription" || fatal 'We have no idea how to remove $prescription (checked in $psdir and $prsdir)'
            __epm_play_run "$prescription" --remove || fatal "There was some error during run the script."
        fi
    done
}


__check_product_alt()
{
    grep -q -E "^PRODUCTALT=" $psdir/$1.sh
}

__get_fast_short_list_app()
{
    local arch="$1"
    [ -n "$arch" ] || fatal
    local IGNOREi586
    [ "$arch" = "x86_64" ] && IGNOREi586='NoNo' || IGNOREi586='i586-'
    grep -L -E "^DESCRIPTION=(''|\"\")" $psdir/*.sh | xargs grep -l -E "^SUPPORTEDARCHES=(''|\"\"|.*\<$arch\>)" | xargs basename -s .sh | grep -v -E "(^$IGNOREi586|^common)"
}

__get_fast_int_list_app()
{
    local arch="$1"
    [ -n "$arch" ] || fatal
    local IGNOREi586
    local RIFS=$'\x1E'
    [ "$arch" = "x86_64" ] && IGNOREi586='NoNo' || IGNOREi586='i586-'
    grep -l -E "^SUPPORTEDARCHES=(''|\"\"|.*\<$arch\>)" $psdir/*.sh | xargs grep -oP "^DESCRIPTION=[\"']*\K[^\"']+"  | sed -e "s|.*/\(.*\).sh:|\1$RIFS|" | grep -v -E "(^$IGNOREi586|^common|#.*$)"
}

# Suggest similar apps using fzf fuzzy search
# Args: app_name
__epm_play_suggest_similar_apps()
{
    local app="$1"
    local arch="$SYSTEMARCH"

    # need fzf for fuzzy search
    is_command fzf || return 1

    local list
    list="$(__get_fast_short_list_app $arch)"
    [ -z "$list" ] && return 1

    [ -n "$verbose" ] && showcmd fzf -i -f "$app"
    local similar
    similar="$(echo "$list" | fzf -i -f "$app" 2>/dev/null | head -5)"
    [ -z "$similar" ] && return 1

    echo ""
    echo "Perhaps you meant:"
    echo "$similar" | sed 's/^/  /'
}


__epm_play_list()
{
    local psdir="$1"
    local extra="$2"
    local i
    local RIFS=$'\x1E'
    local arch="$SYSTEMARCH"

    if [ -n "$short" ] && [ -z "$extra" ] ; then
        __get_fast_short_list_app $arch
        return
    fi
    if [ -n "$short" ] ; then
        for i in $(__get_fast_short_list_app $arch) ; do
            echo "$i"
            if __check_product_alt $i ; then
                for j in $(__run_script "$i" "--product-alternatives" </dev/null) ; do
                    echo "  $i=$j"
                done
            fi
        done
        return
    fi

    if [ -n "$quiet" ] && [ -z "$extra" ] ; then
        __get_fast_int_list_app $arch | sed -e "s|$RIFS| - |"
        return
    fi

    __get_fast_int_list_app $arch | while IFS=$'\x1E' read -r app desc; do
        if [ -n "$quiet" ] ; then
            printf "%s - %s\n" "$app" "$desc"
        else
            printf "  %-25s - %s\n" "$app" "$desc"
        fi
        if [ -n "$extra" ] && __check_product_alt $app ; then
            local j
            for j in $(__run_script "$app" "--product-alternatives" </dev/null) ; do
                if [ -n "$quiet" ] ; then
                    printf "%s - %s\n" "$app=$j" "$desc"
                else
                    printf "  %-25s - %s\n" "$app=$j" "$desc"
                fi
            done
        fi
    done
}


__epm_play_search()
{
    local pattern="$1"
    local arch="$SYSTEMARCH"
    local RIFS=$'\x1E'

    __get_fast_int_list_app $arch | grep -i "$pattern" | while IFS=$'\x1E' read -r app desc; do
        printf "  %-25s - %s\n" "$app" "$desc"
    done
}
