#!/bin/sh
#
# Copyright (C) 2012, 2014, 2016-2017, 2023  Etersoft
# Copyright (C) 2012, 2014, 2016-2017, 2023  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/>.
#

# copied from korinf/tools/run-script/scripts/update

load_helper epm-sh-warmup
load_helper epm-check_updated_repo

# TODO: restore mirroring
get_latest_version()
{
    URL="https://eepm.ru/app-versions"
    #update_url_if_need_mirrored
    local var
    var="$(fetch_url "$URL/$1")" || return
    echo "$var" | head -n1 | cut -d" " -f1
}

__check_for_epm_version()
{
    [ -n "$quiet" ] || info 'Checking for latest EPM version in Korinf repository... '
    local latest="$(get_latest_version eepm)"
    [ -z "$latest" ] && return 1
    local res="$(epm print compare "$EPMVERSION" "$latest")"
    [ "$res" = "-1" ] && return 0
    return 1
}

__notify_about_epm_version()
{
    # skip update checking for eepm from repo (ALT bug #44314)
    epm status --original eepm && return 1

    __check_for_epm_version && info 'Latest EPM version is $latest. You have version $EPMVERSION running.' && info "You can update eepm with \$ epm ei command."
}

__save_available_packages()
{
    [ -d "$epm_vardir" ] || return 0

    # TODO: ignore in docker
    # update list only if the system supports bash completion
    [ -d /etc/bash_completion.d ] || return 0

    # HACK: too much time (5 minutes) on deb systems in a docker
    # [ $PMTYPE = "apt-dpkg" ] && return 0

    info "Retrieving list of all available packages (for autocompletion) ..."
    # can ask sudo later
    set_sudo
    load_helper epm-list_available
    short=--short update=update epm_list_available | sort | sudorun tee $epm_vardir/available-packages >/dev/null
}

__epm_update_content_index()
{
case $BASEDISTRNAME in
    "alt")
        load_helper epm-sh-altlinux-contents-index
        update_alt_contents_index
        return
        ;;
esac

case $PMTYPE in
    apt-dpkg)
        is_command apt-file || return 0
        try_assure_exists apt-file || return 0
        sudocmd apt-file update
        ;;
esac

}

__epm_list_content_index()
{
case $BASEDISTRNAME in
    "alt")
        load_helper epm-sh-altlinux-contents-index
        cat $ALT_CONTENTS_INDEX_LIST
        return
        ;;
esac

}

__epm_update()
{

    info "Running update the package index files from remote package repository database ..."

local ret=0
warmup_hibase

case $PMTYPE in
    apm-rpm)
        sudocmd apm system update
        return
        ;;
esac

case $BASEDISTRNAME in
    "alt")
        # TODO: hack against cd to cwd in apt-get on ALT
        cd /
        local APTOPTIONS="$dryrun $(subst_option non_interactive -y) $(subst_option debug "-o Acquire::Verbose=1 -o Debug::pkgAcquire::Auth=1 -o Debug::identcdrom=1 -o Debug::Acquire::http=1 ")"
        sudocmd apt-get update $APTOPTIONS
        ret="$?"
        cd - >/dev/null
        if [ "$ret" != "0" ] && [ -z "$quiet" ] ; then
            warning "There are some errors with repo info updating. Check apt repos:"
            docmd epm repo list
            warning "Also check if you have an internet connection (ping to the problem site)"
        fi
        return $ret
        ;;
esac


case $PMTYPE in
    apt-rpm)
        # TODO: hack against cd to cwd in apt-get on ALT
        cd /
        sudocmd apt-get update
        ret="$?"
        cd - >/dev/null
        return $ret
        ;;
    apt-dpkg)
        sudocmd apt-get update || return
        # apt-get update retrieve Contents file too
        #sudocmd apt-file update
        ;;
    apm-rpm)
        sudocmd apm system update
        ;;
    packagekit)
        docmd pkcon refresh
        ;;
    #snappy)
    #    sudocmd snappy
    #    ;;
    aptitude-dpkg)
        sudocmd aptitude update || return
        ;;
    yum-rpm)
        sudocmd yum makecache
        ;;
    dnf-rpm)
        sudocmd dnf makecache
        ;;
    dnf5-rpm)
        sudocmd dnf5 makecache
        ;;
    urpm-rpm)
        sudocmd urpmi.update -a
        ;;
    pacman)
        sudocmd pacman -S -y
        sudocmd pacman -F -y
        ;;
    aura)
        sudocmd aura -A -y
        ;;
    zypper-rpm)
        sudocmd zypper $(subst_option non_interactive --non-interactive) refresh
        ;;
    emerge)
        sudocmd emerge --sync
        ;;
    slackpkg)
        sudocmd /usr/sbin/slackpkg -batch=on update
        ;;
    deepsolver-rpm)
        sudocmd ds-update
        ;;
    npackd)
        sudocmd packdcl detect # get packages from MSI database
        ;;
    homebrew)
        docmd brew update
        ;;
    opkg)
        sudocmd opkg update
        ;;
    eopkg)
        sudocmd eopkg update-repo
        ;;
    stplr)
        sudocmd stplr refresh
        ;;
    pisi)
        sudocmd pisi update-repo
        ;;
    apk)
        sudocmd apk update
        ;;
    nix)
        sudocmd nix-channel --update
        ;;
    pkgsrc)
        # portsnap extract for the first time?
        sudocmd portsnap fetch update
        ;;
    aptcyg)
        sudocmd apt-cyg update
        ;;
    xbps)
        sudocmd xbps-install -S
        ;;
    winget)
        sudocmd winget source update
        ;;
    *)
        fatal 'Have no suitable update command for $PMTYPE'
        ;;
esac
}


epm_update()
{
    if [ "$1" = "--help" ] ; then
        message "Usage: epm update [options]
    Options:
        --content-index       Update content index only
        --check-apt-db-days   Check APT DB update status
"
        return
    fi

    if [ "$1" = "--list-content-index" ] ; then
        __epm_list_content_index
        return
    fi
    if [ "$1" = "--content-index" ] ; then
        __epm_update_content_index
        return
    fi
    if [ "$1" = "--check-apt-db-days" ] ; then
        __epm_check_apt_db_days && info "APT DB is up to date"
        return
    fi

    # update with args is the alias for upgrade
    #if [ -n "$*" ] ; then
    #    epm upgrade "$@"
    #    return
    #fi

    [ -n "$quiet" ] || __notify_about_epm_version

    __epm_update "$@" || return

    __epm_touch_pkg

    __save_available_packages

    __epm_update_content_index

    return 0
}
