#!/bin/sh
#
# Copyright (C) 2015, 2017, 2019, 2020  Etersoft
# Copyright (C) 2015, 2017, 2019, 2020  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/>.
#

# TODO
epm_vardir=/var/lib/eepm


__epm_prescription_run()
{
    local script="$psdir/$1.sh"
    shift
    local option="$1"

    if [ ! -x "$script" ] ; then
        fatal "Can't find $script prescription."
    fi

    # allow use EGET in the scripts
    __set_EGET
    # also we will have DISTRVENDOR there
    export PATH=$PROGDIR:$PATH

    #info "Running $($script --description 2>/dev/null) ..."
    docmd $script $option
}

epm_prescription()
{

local psdir="$CONFIGDIR/prescription.d"

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
    cat <<EOF
Options:
    APP            - install APP
    --list         - list all installed apps
    --list-all     - list all available apps
EOF
    exit
fi

if [ "$1" = "--list" ] || [ "$1" = "--installed" ] ; then
    shift
    echo "Installed:"
    local i
    for i in $(__list_installed_app) ; do
        printf "  %-20s - %s\n" "$i" "$($psdir/$i.sh --description 2>/dev/null)"
    done
    exit
fi

if [ "$1" == "--list-all" ] || [ -z "$*" ] ; then
    echo "Run with a name of a prescription to run:"
    for i in $psdir/*.sh ; do
        printf "  %-20s - %s\n" "$(basename $i .sh)" "$($i --description 2>/dev/null)"
    done
    echo
    echo "run epm prescription --list to list installed only"
    exit
fi

__epm_prescription_run "$1" --run
}