#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
. gettext.sh
TEXTDOMAIN="elive-tools"
export TEXTDOMAIN



usage(){
    echo -e "Usage: $(basename $BASH_SOURCE) packagename [--force]"
}

main(){
    # pre {{{
    local packagename line package_version_installed package_version_newer_found_maybe url_package_dir url_repository version is_mode_force arg


    # Usage
    if [[ -z "${1}" ]] ; then
        usage
        exit
    fi

    for arg in "$@"
    do
        case "$arg" in
            -f|--force)
                is_mode_force=1
                ;;
            -a|--automated)
                is_automated=1
                is_quiet=1
                ;;
            -h|--help)
                usage
                exit
                ;;
            -q|--quiet)
                is_quiet=1
                ;;
            -c|--check)
                # check only and exit, return value is used
                is_check_only=1
                ;;
            *)
                if [[ -n "$packagename" ]] ; then
                    # this tool is made to only install one package at time, hum... so things like eliveinstaller checks the return status, and this depends on a single one
                    el_error "this tool only allows one package argument, no more. Using the first given one"
                else
                    packagename="$arg"
                fi
                ;;
        esac
    done

    el_debug "looking for updates for the package '${packagename}' "
    url_repository="$( apt-cache madison ${packagename} | tr ' ' '\n' | grep -F http | head -1 )"

    # check if exist or apt-get update
    if [[ -z "$url_repository" ]] ; then
        if ((is_quiet)) ; then
            if [[ "$UID" = 0 ]] ; then
                apt-get update || apt-get update
            else
                el_sudo bash -c "apt-get update || apt-get update"
            fi
        else
            el_aptget_update
        fi
    fi

    url_repository="$( apt-cache madison ${packagename} | tr ' ' '\n' | grep -F http | head -1 )"
    if [[ -z "$url_repository" ]] ; then
        NOREPORTS=1 el_warning "Package $packagename not found in the repos, ignoring it..."
        exit 1
    fi


    # check internet
    if ! el_verify_internet ; then
        el_explain 1 "No internet found, ignoring checking of newer packages available"
        exit 1
    fi

    # check repo url
    if ! el_check_variables "url_repository" ; then
        el_error "no url found for ${packagename} package, ignoring check in $(basename $0)"
        exit 1
    fi

    if ! el_dependencies_check "apt-get|apt-cache|zenity|dpkg" ; then
        exit 1
    fi


    # }}}

    package_version_installed="$( el_apt_package_version_get "$packagename" installed full )"

    # first pass, check if we can have a possible candidate (fuzzy mode) {{{
    while read -ru 3 line
    do
        url_package_dir="${url_repository%/}/${line%/*}/"

        # compare all teh versions found with a simple curl with the installed version
        while read -ru 3 version
        do
            # cleanup var and url-decode it
            read -r version <<< "$version"
            #version="$( hURL -us --nocolor "$version" )"
            version="$( printf "$( echo "$version" | sed -e 's|%|\\x|g' )" )"

            if dpkg --compare-versions "${version}" gt "${package_version_installed}" 2>/dev/null ; then
                package_version_newer_found_maybe=1
            fi
        done 3<<< "$( curl -s "${url_package_dir}" | grep -F href | sed -e 's|^.*href="||g' -e 's|".*$||g' | grep '\.deb$' | cut -d'_' -f2 | sort -u )"

    done 3<<< "$( apt-cache show "${packagename}" 2>/dev/null | grep -F "Filename:" | sed -e 's|^Filename: ||g' | sort -u )"



    # - first pass, check if we can have a possible candidate (fuzzy mode) }}}
    # checking results and deciding {{{
    # nothing found in a first shot?
    if ! ((package_version_newer_found_maybe)) ; then
        # return false if we have not updated or found anything
        exit 1
    fi

    # return true always, if we arrived here
    if ((is_check_only)) ; then
        exit 0
    fi


    # - checking results and deciding }}}

    # make sure that we update caches or we will be unable to install it
    if ((is_quiet)) ; then
        if [[ "$UID" = 0 ]] ; then
            apt-get update || apt-get update
        else
            el_sudo bash -c "apt-get update || apt-get update"
        fi
    else
        el_aptget_update force
    fi

    # install new package if found
    if el_package_newer_check "${packagename}" ; then

        local message_upgrade_please message_upgrade_force
        message_upgrade_please="$( printf "$( eval_gettext "Found a newer version of %s. Update it?" )" "${packagename%:*}" )"

        message_upgrade_force="$( printf "$( eval_gettext "The package %s needs to be updated." )" "${packagename%:*}" )"

        # install
        if ((is_automated)) ; then
            if [[ "$UID" = 0 ]] ; then
                if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get -f install ; then
                    el_error "problem with apt-get -f install"
                fi
                if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -y ${packagename} ; then
                    el_error "problem with apt-get install -y $packagename"
                fi
            else
                if el_check_sudo_automated ; then
                    el_sudo bash -c "export TERM=screen-256color ; export DEBIAN_FRONTEND=noninteractive ; export DEBIAN_PRIORITY=critical ; export DEBCONF_NONINTERACTIVE_SEEN=true ; export DEBCONF_NOWARNINGS=true ; apt-get -f install ; apt-get -f install -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold -y ${packagename}"
                else
                    el_error "$(basename $0) called in automated mode and we are non-root, how we should proceed? ignoring..."
                fi
            fi
        else
            if [[ -n "$DISPLAY" ]] ; then
                if ((is_mode_force)) ; then
                    if ! ((is_quiet)) ; then
                        zenity --info --text="$message_upgrade_force" || true
                    fi
                    if ! el_dependencies_install "$packagename" ; then
                        exit 1
                    fi
                    exit 0
                else
                    if ((is_quiet)) ; then
                        if ! el_dependencies_install "$packagename" ; then
                            exit 1
                        fi
                        exit 0
                    else
                        if zenity --question --text="$message_upgrade_please" ; then
                            if ! el_dependencies_install "$packagename" ; then
                                exit 1
                            fi
                            exit 0
                        else
                            exit 1
                        fi
                    fi
                fi

            else
                if ((is_interactive)) ; then
                    if ((is_mode_force)) ; then
                        echo -e "The package $packagename needs to be updated.\nInsert root/admin password:"
                        su -c "TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install $packagename" root
                        exit 0
                    else
                        if el_confirm "$message_upgrade_please" ; then
                            echo -e "Please insert root/admin password:"
                            su -c "TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install $packagename" root
                            exit 0
                        else
                            exit 1
                        fi
                    fi
                else
                    if [[ "$UID" = 0 ]] ; then
                        if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get -f install ; then
                            el_error "problem with apt-get -f install"
                        fi
                        if ! TERM=screen-256color DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get install -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -y ${packagename} ; then
                            el_error "problem with apt-get install -y $packagename"
                        fi
                    else
                        el_error "$(basename $0) called outside graphical system and outside terminal and non-root mode, how we should proceed? ignoring..."
                    fi
                fi
            fi
        fi
    else
        exit 1
    fi


}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker expandtab :
