#!/bin/sh
#
# Copyright (C) 2012-2021  Etersoft
# Copyright (C) 2012-2021  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/>.
#

PROGDIR=$(dirname "$0")
PROGNAME=$(basename "$0")
[ "$PROGDIR" = "." ] && PROGDIR=$(pwd)
if [ "$0" = "/dev/stdin" ] || [ "$0" = "sh" ] ; then
    PROGDIR=""
    PROGNAME=""
fi

# will replaced to /usr/share/eepm during install
SHAREDIR=$PROGDIR
CONFIGDIR=$PROGDIR/..

load_helper()
{
    local CMD="$SHAREDIR/$1"
    # do not use fatal() here, it can be initial state
    [ -r "$CMD" ] || { echo "FATAL: Have no $CMD helper file" ; exit 1; }
    # shellcheck disable=SC1090
    . $CMD
}


load_helper epm-sh-functions

#PATH=$PATH:/sbin:/usr/sbin

set_pm_type

#set_sudo

check_tty

#############################

phelp()
{
	echo "
Usage: yum [options] COMMAND

List of Commands:

$(get_help HELPCMD | sed -e 's@|@,@g')

Options:
$(get_help HELPOPT | sed -e 's@|@,@g')

"
}

print_version()
{
        echo "EPM package manager version @VERSION@  https://wiki.etersoft.ru/Epm"
        echo "Running on $($DISTRVENDOR -e) ('$PMTYPE' package manager uses '$PKGFORMAT' package format)"
        echo "Copyright (c) Etersoft 2012-2021"
        echo "This program may be freely redistributed under the terms of the GNU AGPLv3."
}


EPMVERSION=@VERSION@
verbose=
quiet=
nodeps=
noremove=
dryrun=
force=
repack=
inscript=
scripts=
noscripts=
short=
direct=
sort=
non_interactive=
skip_installed=
skip_missed=
show_command_only=
epm_cmd=
pkg_files=
pkg_dirs=
pkg_names=
pkg_urls=
quoted_args=

# load system wide config
[ -f /etc/eepm/eepm.conf ] && . /etc/eepm/eepm.conf


check_command()
{
    # do not override command
    [ -z "$epm_cmd" ] || return

# Bellow original commands to be mapped into eepm are taken from the following places:
# - yum help
# - source code of dnf 4.x, dnf/cli/commands/*.py, "aliases = (<...>)" (yum-dnf will understand them)
# - default upstream configs of aliases in dnf 4.x (output of `dnf alias`)
# HELPCMD:
    case $1 in
    check)                    # HELPCMD: Check for problems in the rpmdb
        epm_cmd=check
        ;;
    check-update)             # HELPCMD: Check for available package updates
        epm_cmd=upgrade
        ;;
    clean)                    # HELPCMD: Remove cached data
        epm_cmd=clean
        ;;
    deplist)                  # HELPCMD: List a package's dependencies
        # TODO: hilevel in any case
        epm_cmd=requires
        ;;
    distribution-synchronization | distro-sync | distrosync | dsync | dup) # HELPCMD: Synchronize installed packages to the latest available versions
        # TODO: distro-sync can either upgrade or downgrade packages,
        # apt-get with pinned priorities of repositiories would be a replacement
        fatal "Is not supported"
        ;;
    downgrade | dg)           # HELPCMD: downgrade a package
        epm_cmd=downgrade
        ;;
    remove | rm | erase)      # HELPCMD: Remove a package or packages from your system
        epm_cmd=remove
        ;;
    groupinfo)                # HELPCMD: Display details about a package group
        fatal "Is not supported"
        ;;
    groupinstall)             # HELPCMD: Install the packages in a group on your system
        fatal "Is not supported"
        ;;
    grouplist)                # HELPCMD: List available package groups
        fatal "Is not supported"
        ;;
    groupremove)              # HELPCMD: Remove the packages in a group from your system
        fatal "Is not supported"
        ;;
    help)                     # HELPCMD: Display a helpful usage message
        help=1
        phelp
        exit 0
        ;;
    history | hist)           # HELPCMD: Display, or use, the transaction history
        fatal "Is not supported"
        ;;
    info)                     # HELPCMD: Display details about a package or group of packages
        epm_cmd=info
        ;;
    install | in | localinstall) # HELPCMD: Install a package or packages on your system
        epm_cmd=install
        ;;
    list)                     # HELPCMD: List a package or groups of packages
        # TODO: support base options (see list -h), all available packages by default
        epm_cmd=packages
        ;;
    load-transaction)         # HELPCMD: load a saved transaction from filename
        fatal "Is not supported"
        ;;
    makecache | refresh)      # HELPCMD: Generate or update the metadata cache
        epm_cmd=update
        ;;
    provides)                 # HELPCMD: Find what package provides the given value
        # TODO: hilevel in any case
        epm_cmd=provides
        ;;
    reinstall | rei)          # HELPCMD: reinstall a package
        epm_cmd=reinstall
        ;;
    repolist | repoinfo)      # HELPCMD: Display the configured software repositories
        epm_cmd=repolist
        ;;
    resolvedep)               # HELPCMD: Determine which package provides the given dependency
        epm_cmd=whatprovides
        ;;
    search | se)              # HELPCMD: Search package details for the given string
        epm_cmd=search
        ;;
    shell | sh)               # HELPCMD: Run an interactive yum shell
        # TODO: not full compatible
        apt-shell
        ;;
    update)                   # HELPCMD: Update a package or packages on your system
        epm_cmd=install
        ;;
    upgrade)                  # HELPCMD: Update packages taking obsoletes into account
        epm_cmd=upgrade
        ;;
    version)                  # HELPCMD: Display a version for the machine and/or available repos.
        echo "Installed: $DISTRVERSION/$DISTRARCH"
        echo "version"
        exit 0
        ;;
    *)
        return 1
        ;;
    esac
    return 0
}

check_option()
{
    case $1 in
    -h|--help)            # HELPOPT: show this help message and exit
        help=1
        phelp
        exit 0
       ;;
    -t|--tolerant)        # HELPOPT: be tolerant of errors
        fatal "Is not supported"
        ;;
    -C|--cacheonly)       # HELPOPT: run entirely from system cache, don't update cache
        fatal "Is not supported"
        ;;
    --showduplicates)     # HELPOPT: show duplicates, in repos, in list/search commands
        fatal "Is not supported"
        ;;
    --quiet)              # HELPOPT: quiet operation
        quiet=1
        ;;
    -v|--verbose)         # HELPOPT: verbose operation
        verbose="--verbose"
        ;;
    -y|--assumeyes)       # HELPOPT: answer yes for all questions
        non_interactive="--auto"
        ;;
    --assumeno)           # HELPOPT: answer no for all questions
        fatal "Is not supported"
        ;;
    --version)            # HELPOPT: show Yum version and exit
        print_version
        exit 0
        ;;
#    --installroot=[path]  set install root
#  --enablerepo=[repo]   enable one or more repositories (wildcards allowed)
#  --disablerepo=[repo]  disable one or more repositories (wildcards allowed)
#  -x [package], --exclude=[package]
#                        exclude package(s) by name or glob
#  --disableexcludes=[repo]
#                        disable exclude from main, for a repo or for
#                        everything
#  --obsoletes           enable obsoletes processing during updates
#  --noplugins           disable Yum plugins
#  --nogpgcheck          disable gpg signature checking
#  --skip-broken         skip packages with depsolving problems
#  --releasever=RELEASEVER
#                        set value of $releasever in yum config and repo files
#  --downloadonly        don't update, just download
#  --downloaddir=DLDIR   specifies an alternate directory to store packages
#  --setopt=SETOPTS      set arbitrary config and repo options
    *)
        return 1
        ;;
    esac
    return 0
}

# TODO: skip for commands where we don't need parse args

check_filenames()
{
    local opt
    for opt in "$@" ; do
        # files can be with full path or have extension via .
        if [ -f "$opt" ] && echo "$opt" | grep -q "[/\.]" ; then
            has_space "$opt" && warning "There are space(s) in filename '$opt', it is not supported. Skipped" && continue
            pkg_files="$pkg_files $opt"
        elif [ -d "$opt" ] ; then
            has_space "$opt" && warning "There are space(s) in directory path '$opt', it is not supported. Skipped" && continue
            pkg_dirs="$pkg_dirs $opt"
        elif echo "$opt" | grep -q "^[fhtps]*://" ; then
            has_space "$opt" && warning "There are space(s) in URL '$opt', it is not supported. Skipped" && continue
            pkg_urls="$pkg_urls $opt"
        else
            has_space "$opt" && warning "There are space(s) in package name '$opt', it is not supported. Skipped." && continue
            pkg_names="$pkg_names $opt"
        fi
        quoted_args="$quoted_args \"$opt\""
    done
}

FLAGENDOPTS=
for opt in "$@" ; do
    [ "$opt" = "--" ] && FLAGENDOPTS=1 && continue
    if [ -z "$FLAGENDOPTS" ] ; then
        check_command "$opt" && continue
        check_option "$opt" && continue
    fi
    # Note: will parse all params separately (no package names with spaces!)
    check_filenames "$opt"
done

pkg_files=$(strip_spaces "$pkg_files")
pkg_dirs=$(strip_spaces "$pkg_dirs")
# in common case dirs equals to names only suddenly
pkg_names=$(strip_spaces "$pkg_names $pkg_dirs")
pkg_urls=$(strip_spaces "$pkg_urls")

pkg_filenames=$(strip_spaces "$pkg_files $pkg_names")

# Just debug
#echover "command: $epm_cmd"
#echover "pkg_files=$pkg_files"
#echover "pkg_names=$pkg_names"

# Just printout help if run without args
if [ -z "$epm_cmd" ] ; then
    phelp
    echo
    fatstr="No such command: $*. Please use /usr/bin/yum --help"
    [ -n "$*" ] || fatstr="You need to give some command"
    # TODO: https://bugzilla.altlinux.org/show_bug.cgi?id=39093
    # Почему-то только в этом файле/пакете использование info вызывает зависимость на пакет info
    #info "$fatstr."
    echo "$fatstr."
    exit 1
fi

[ -n "$verbose$EPM_VERBOSE" ] && showcmd "$0 $*"

# Run helper for command with natural args
load_helper epm-$epm_cmd
eval epm_$epm_cmd $quoted_args
# return last error code (from subroutine)