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

__is_repo_info_downloaded()
{
    case $PMTYPE in
        apt-*)
            #if [ -r /var/cache/apt ] ; then
            #    sudorun test -r /var/cache/apt/pkgcache.bin || return
            #fi
            ;;
        *)
            ;;
    esac
    return 0
}

__is_repo_info_uptodate()
{
    case $PMTYPE in
        apt-*)
            # apt-deb do not update lock file date
            #if $SUDO test -r /var/lib/apt/lists ; then
                local LOCKFILE=/var/lib/apt/lists
                sudorun test -r $LOCKFILE || return
                # if repo older than 1 day, return false
                # find print string if file is obsoleted
                test -z "$(find $LOCKFILE -maxdepth 0 -mtime +1)" || return
            #fi
            ;;
        *)
            ;;
    esac
    return 0
}

update_repo_if_needed()
{
    # TODO: needs careful testing
    return
    # check if we need skip update checking
    if [ "$1" = "soft" ] && ! set_sudo nofail ; then
        # if sudo requires a password, skip autoupdate
        info "can't use sudo, so skip repo status checking"
        return 1
    fi

    cd / || fatal
    if ! __is_repo_info_downloaded || ! __is_repo_info_uptodate ; then
        load_helper epm-update
        # FIXME: cleans!!!
        epm_update
    fi
    cd - >/dev/null || fatal

}

# save manually installed packages
save_installed_packages()
{
	[ -d /var/lib/rpm ] || return 0
	estrlist list "$@" | sudorun tee /var/lib/rpm/EPM-installed >/dev/null
}

check_manually_installed()
{
	[ -r /var/lib/rpm/EPM-installed ] || return 1
	grep -q -- "^$1\$" /var/lib/rpm/EPM-installed
}

skip_manually_installed()
{
	local i
	for i in "$@" ; do
		check_manually_installed "$i" && continue
		echo "$i"
	done
}