#!/bin/bash
# ==============================================================================
# HOW TO CREATE HOOKS FOR ELIVE-UPGRADER
# ==============================================================================
# Hooks are organized by Debian release codenames and version numbers.
#
# Directory Structure:
#   /usr/lib/elive-upgrader/hooks-<codename>/<version>/[root|user]/
#
#   Example:
#     /usr/lib/elive-upgrader/hooks-bookworm/3.8.50.01/user/
#
# Hook Types & Execution Order:
#   Inside the [root|user] directories, files are executed/processed in this order:
#
#   1. pre-*.sh
#      - Executed during the "pre" phase. Must be executable (chmod +x).
#
#   2. packages-to-remove.txt
#      - List of packages to remove (one per line or space-separated).
#
#   3. packages-to-install.txt
#      - List of packages to install (one per line or space-separated).
#
#   4. packages-to-upgrade.txt
#      - List of packages to upgrade (only if already installed).
#
#   5. *.sh (Deprecated)
#      - Executed if they don't start with "pre-" or "post-".
#
#   6. CHANGELOG.txt / pre-CHANGELOG.txt / post-CHANGELOG.txt
#      - Text files containing release notes shown to the user.
#
#   7. post-*.sh
#      - Executed during the "post" phase. Must be executable (chmod +x).
#
#   8. debian-upgrade (Must be in 'root' directory of distro-upgrade hook)
#      - Required marker file to activate distro-upgrade hooks.
#      - Contains the upgrade tier: "alpha", "beta", or "stable".
#      - "alpha" forces debug report generation (FORCE_REPORTS="1") and requires betatester mode.
#      - "beta" requires Premium membership.
#      - "stable" is available to all users.
#
#   9. debian-upgrade-packages-to-remove.txt
#      - List of blocking packages to remove BEFORE starting the distro-upgrade.
#      - Executed during pre-hooks before APT sources update and before package downloads/upgrades.
#
#   10. debian-upgrade-pre-script.sh
#      - Script executed BEFORE starting the distro-upgrade (during pre-hooks).
#      - Runs after debian-upgrade-packages-to-remove.txt and before APT sources update.
#
#   11. debian-upgrade-packages-to-install.txt
#      - List of supporting packages to install AFTER the full upgrade step completes, BEFORE rebooting.
#      - Runs after full-upgrade, kernel install, update-initramfs, and update-grub.
#
#   12. debian-upgrade-packages-to-install-if-before.txt
#      - List of packages to install in one single shot AFTER the full upgrade step completes,
#        but ONLY if they were present on the system BEFORE the upgrade.
#      - Supports wildcards (e.g., gimp*) and package names with architecture specifications.
#      - Uses the saved pre-upgrade package list (/var/log/elive-upgrader/debian-upgrade-packages-before-*.txt).
#      - Packages are precached (downloaded) during the predownload phase before reboot.
#      - Installation is executed with --no-remove so apt will fail rather than remove conflicting packages.
#
#   13. debian-upgrade-packages-to-remove-post.txt
#      - List of packages to remove AFTER completing the full upgrade step, BEFORE rebooting.
#      - Runs during post-hooks before installing debian-upgrade-packages-to-install.txt.
#
#   14. debian-upgrade-post-script.sh
#      - Script executed AFTER completing the full upgrade step, BEFORE rebooting.
#      - Runs during post-hooks right after debian-upgrade-packages-to-install.txt.
#
#   15. debian-upgrade-packages-to-remove-if-not-before.txt
#      - List of packages to remove near the end of the upgrade process (BEFORE reboot),
#        or on first boot as a fallback, if they were NOT present on the system before the upgrade.
#      - Supports wildcards (e.g., exim4*).
#
# ==============================================================================
# DIFFERENCE BETWEEN 'root' AND 'user' HOOK DIRECTORIES
# ==============================================================================
# Hooks are split into 'root' and 'user' directories to separate system-wide
# administration tasks from user-specific desktop environment configurations.
#
# 1. 'root' Directory Hooks:
#    - Triggered: Run by the system-wide upgrader service (root context) during
#      system boot or when running system-wide upgrades (e.g., elive-upgrader-root).
#    - Context: Executed with full root privileges.
#    - Execution: Run only once system-wide.
#    - When to use:
#      * Installing, upgrading, or removing system packages.
#      * Modifying system-wide configuration files in /etc, /var, /boot, etc.
#      * Rebuilding initramfs, updating GRUB, or managing system services.
#      * Performing system-wide cleanups or hardware-specific configurations.
#
# 2. 'user' Directory Hooks:
#    - Triggered: Run within the user's graphical desktop session context upon
#      login (via autostart desktop entries or user-level upgrader triggers).
#    - Context: Executed with the logged-in user's privileges (non-root).
#    - Execution: Run again per each user on the system.
#    - When to use:
#      * Modifying user-specific configurations in $HOME (e.g., ~/.config, ~/.local).
#      * Changing desktop themes, wallpapers, panel settings, or application configs.
#      * Showing graphical notifications, dialogs, or changelogs to the user.
#      * Triggering interactive prompts (like the distro upgrade prompt) that
#        require user consent or interaction within the GUI.
# ==============================================================================

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

# Lock system (good one) {{{
if [[ "$1" = "--enable-distro-upgrade" ]] || [[ "$1" = "--cancel-distro-upgrade" ]] || [[ "$1" = "--distro-upgrade-status" ]] || [[ "$1" = "--ping" ]] ; then
    # Bypass lock for quick/non-disruptive commands
    :
else
    lockfile="/tmp/.$(basename $0)-${USER}.lock"
    #set -x

    exit_ok(){
        rm -f "$lockfile"

        #killall apt-get 2>/dev/null 1>&2 || true
        tmux kill-window -t Upgrade 2>/dev/null 1>&2 || true

        #while read -ru 3 line
        #do
            #[[ -z "$line" ]] && continue
            #kill "$line" 2>/dev/null 1>&2 || true
        #done 3<<< "$( ps ux | grep -v grep | grep -E "(bash.*apt-get|apt-get.*dist-upgrade)" )"
    }
    exit_error(){
        rm -f "$lockfile"

        #tmux kill-session -t elive-upgrader
        tmux kill-window -t Upgrade 2>/dev/null 1>&2 || true

        #killall apt-get 2>/dev/null 1>&2 || true

        #while read -ru 3 line
        #do
            #[[ -z "$line" ]] && continue
            #kill "$line" 2>/dev/null 1>&2 || true
        #done 3<<< "$( ps ux | grep -v grep | grep -E "(bash.*apt-get|apt-get.*dist-upgrade)" )"
        exit 1
    }

    if [[ -r "$lockfile" ]] ; then
        PROCCESS="$(cat $lockfile)"
    else
        PROCCESS=" "
    fi
    if (ps up $PROCCESS) 1>/dev/null 2>&1 ; then
        NOREPORTS=1 el_error "$(basename $0) already running"
        exit
    else
        echo $$ > "$lockfile"
    fi

    # traps needs to be after the lock verification, in order to not remove it when we are already running
    trap "exit_ok" EXIT
    trap "exit_error" 1 2 3 5 6 14 ERR

    # SET the lock file
    echo "$$" > "$lockfile"
fi
# end lock system }}}

# run fixes for apt in case we have lead to broken states
apt_fixes(){
    local is_failed
    # always update before to run (if the package has been updated we want to fetch new code too)
    source /usr/lib/elive-upgrader/functions.sh

    # Fix unsupported keyring filetypes (e.g., marillat key)
    if [[ -f /etc/apt/trusted.gpg.d/marillat.key.binary.asc ]]; then
        el_info "Fixing marillat keyring filetype..."
        if command -v gpg &>/dev/null; then
            gpg --dearmor < /etc/apt/trusted.gpg.d/marillat.key.binary.asc > /etc/apt/trusted.gpg.d/marillat.key.binary.gpg 2>/dev/null || true
        fi
        rm -f /etc/apt/trusted.gpg.d/marillat.key.binary.asc
    fi

    # wait unlock
    apt_get moo 1>/dev/null 2>&1

    if ! apt_get -y -f install -q=2 ; then
        sleep 20
        # check for good state
        apt_get check 1>/dev/null

        if ! apt_get -y -f install -q=2 ; then

            # try to reconfigure packages now
            if dpkg --configure -a --force-confold ; then
                if ! apt_get -y -f install -q=2 ; then
                    el_error "$(basename $0) in ${FUNCNAME} with apt-get -y -f install:\n$( DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true  apt-get -y -f install 2>&1 )"
                    is_failed=1
                fi
            else
                el_error "$(basename $0) in ${FUNCNAME} with dpkg --configure -a:\n$( dpkg --configure -a --force-confold 2>&1 )"
                is_failed=1
            fi
        fi
    fi

    if ((is_failed)) ; then
        local message_failed
        message_failed="$( printf "$( eval_gettext "You seem to have broken packages. Open a terminal and run the command '%s'. If the issue persists, consider reinstalling Elive in upgrade mode which keeps your files and settings." )" "apif" )"
        $guitool --error --text="$message_failed" 1>/dev/null 2>&1
        return 1
    fi

    return 0
}
hooks_root_pre(){
    # always update before to run (if the package has been updated we want to fetch new code too)
    source /usr/lib/elive-upgrader/functions.sh

    # set the user as an active member or not
    patreon_members_update

    # hooks: root
    run_hooks "root" "pre"
}

hooks_root_post(){
    # always update before to run (if the package has been updated we want to fetch new code too)
    source /usr/lib/elive-upgrader/functions.sh

    # hooks: root
    run_hooks "root" "post"
}



updates_available_show(){
    local number

    # wait unlock
    apt_get moo 1>/dev/null 2>&1

    # update
    if ! is_quiet=1 el_aptget_update 1>/dev/null 2>&1 ; then
        sleep 10
        if ! is_quiet=1 el_aptget_update ; then
            NOREPORTS=1 el_error "problem with el_aptget_update\n$( apt-get update 2>&1 )"
            return 1
        fi
    fi

    number="$( LC_ALL="$EL_LC_EN" TERM=linux DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical DEBCONF_NONINTERACTIVE_SEEN=true DEBCONF_NOWARNINGS=true apt-get -u upgrade --assume-no --show-upgraded | grep -E "^[[:digit:]]+ upgraded," | tail -1 | awk '{print $1}' )"

    if [[ -n "$number" ]] && echo "$number" | grep -qs "^[[:digit:]]" ; then
        echo "$number"
        return 0
    else
        return 1
    fi
}

upgrade_system(){
    local is_upgraded

    # wait unlock
    el_info "Updating APT lists..."
    apt_get moo 1>/dev/null 2>&1

    if ! ((is_update_ignored)) ; then
        if ! apt_get update -q=2 ; then
            apt_get check 1>/dev/null
            # do not exit if fails, sometimes we have unworking repos but apt update works
            apt_get update -q=2
        fi

        # Check for distro upgrade first as a priority
        local _current_ver _next_codename
        _current_ver="$( cat /etc/debian_version 2>/dev/null | cut -d'.' -f1 )"
        if ! [[ "$_current_ver" =~ ^[0-9]+$ ]]; then
            local current_release_full
            current_release_full="$( cat /etc/debian_version 2>/dev/null )"
            if [[ "$current_release_full" == *"bullseye"* ]]; then
                _current_ver=11
            elif [[ "$current_release_full" == *"bookworm"* ]]; then
                _current_ver=12
            elif [[ "$current_release_full" == *"trixie"* ]]; then
                _current_ver=13
            elif [[ "$current_release_full" == *"forky"* ]]; then
                _current_ver=14
            fi
        fi
        case "$_current_ver" in
            11) _next_codename="bookworm" ;;
            12) _next_codename="trixie" ;;
            13) _next_codename="forky" ;;
            14) _next_codename="duke" ;;
            *) _next_codename="" ;;
        esac
        if [[ -n "$_next_codename" ]] ; then
            local repo_url="https://repo.${_next_codename}.elive.elivecd.org/dists/${_next_codename}/Release"
            if curl --output /dev/null --silent --head --fail "$repo_url"; then
                # Check the upgrade type from the debian-upgrade file
                local upgrade_type=""
                local debian_upgrade_file
                debian_upgrade_file="$( find "${hooks_d}" -path "*/root/debian-upgrade" 2>/dev/null | sort -V | tail -1 )"
                if [[ -f "$debian_upgrade_file" ]]; then
                    upgrade_type="$( tr -d '\r\n ' < "$debian_upgrade_file" )"
                fi

                # Check user eligibility based on upgrade type
                local can_upgrade=0
                case "$upgrade_type" in
                    alpha)
                        if [[ -z "${is_betatester:-}" ]]; then
                            [[ -f /tmp/.elive-upgrader-betatest ]] && is_betatester=1 || is_betatester=0
                        fi
                        if ((is_betatester)); then
                            can_upgrade=1
                        else
                            el_info "This distro upgrade is only available for betatesters."
                        fi
                        ;;
                    beta)
                        if ((is_premium_user)); then
                            can_upgrade=1
                        else
                            el_info "This distro upgrade is only available for Premium users."
                        fi
                        ;;
                    stable)
                        can_upgrade=1
                        ;;
                    *)
                        el_info "No distro upgrade eligibility found for $_next_codename."
                        ;;
                esac

                if ((can_upgrade)); then
                    el_info "A distribution upgrade to $_next_codename is available."
                    el_info "Enabling distro upgrade to $_next_codename..."
                    if /usr/lib/elive-upgrader/debian-upgrader --enable-boot-upgrade "$_next_codename" ; then
                        return 0
                    fi
                fi
            fi
        fi

        # check
        if ! [[ "$( updates_available_show )" -gt 0 ]] ; then
            el_info "$( eval_gettext "No updates available" )"
            return 0
        fi
    fi

    el_info "Upgrading system..."
    # test if we can run in a detached mode, so the user can close terminal without problems
    if [[ -x /usr/bin/tmux ]] && [[ -x /usr/bin/tmux-attach-jobs ]] ; then
        timeout 10 tmux-attach-jobs elive-upgrader stamp "touch '/tmp/.elive-upgrading'" 1>/dev/null
        sleep 1 ; sync
    fi

    # run it, undetached or direct if we don't have tmux feature
    if [[ -e "/tmp/.elive-upgrading" ]] ; then
        rm -f "/tmp/.elive-upgrading" 1>/dev/null 2>&1 || true

        # IMPORTANT: do not use timeout, it will block apt-get
        tmux-attach-jobs elive-upgrader Upgrade "bash -c 'export DEBIAN_FRONTEND=noninteractive ; export DEBIAN_PRIORITY=critical ; export DEBCONF_NONINTERACTIVE_SEEN=true ; export DEBCONF_NOWARNINGS=true ; export UCF_FORCE_CONFFOLD=1 ; export APT_LISTCHANGES_FRONTEND=none ;  apt-get $APTGET_OPTIONS dist-upgrade ; apt-get $APTGET_OPTIONS autoremove ; echo ; echo ; echo -e \"Upgrade DONE\nYou can close the terminal now\" ; sleep 60 '" 1>/dev/null
        sleep 1 ; sync

        # visualize tasks if we have it already not opened
        if ! LC_ALL="$EL_LC_EN" ps ux | grep -v grep | grep -qs "rxvt.*tmux attach" ; then
            urxvt -e bash -c "unset TMUX ; tmux attach -t elive-upgrader"
            is_upgraded=1
        fi
    else
        urxvt -e bash -c "export DEBIAN_FRONTEND=noninteractive ; export DEBIAN_PRIORITY=critical ; export DEBCONF_NONINTERACTIVE_SEEN=true ; export DEBCONF_NOWARNINGS=true ; export UCF_FORCE_CONFFOLD=1 ; export APT_LISTCHANGES_FRONTEND=none ; apt-get $APTGET_OPTIONS dist-upgrade ; apt-get $APTGET_OPTIONS autoremove ; echo ; echo ; echo -e \"Upgrade DONE\nYou can close the terminal\" ; sleep 60 " 1>/dev/null
        is_upgraded=1
    fi

    if ((is_upgraded)) ; then
        # Update: disable entirely the donations asking since we have already one on the post changelog
        # source /etc/elive/settings 2>/dev/null || true
        # if ! ((is_premium_user)) ; then
            # monthly_donations="$( monthly_earnings_patreon_get )"
            # local message_donate_to_continue
            # message_donate_to_continue="$( printf "$( eval_gettext "Your Elive has been upgraded with improvements and fixes. This month we have received so far %s. Would you like to contribute to the amazing Elive project in order to keep it progressing?" )" "$monthly_donations" )"
            # if $guitool  --question --text="$message_donate_to_continue" 1>/dev/null 2>&1 ; then
            #     web-launcher "https://www.patreon.com/elive"
            # fi
        # fi

        el_info "Upgrade finished..."
    fi

    # remove flag
    rm -f "/tmp/.elive-upgrading" 1>/dev/null 2>&1 || true
}

# upgrade bios firmwares
upgrade_firmwares(){
    # pre {{{

    if el_check_dir_has_files "/sys/firmware/efi/" 1>/dev/null 2>&1 ; then
        if el_check_dir_has_files "/sys/firmware/efi/efivars" 1>/dev/null 2>&1 ; then
            is_efi_booted=1

            if [[ -x "$( which efivar )" ]] ; then
                if ! [[ "$( efivar -l 2>/dev/null | wc -l )" -ge 1 ]] ; then
                    unset is_efi_booted
                fi
            fi
        fi
    fi

    if ! el_dependencies_check "fwupdmgr" ; then
        el_info "fwupdmgr is not installed, ignoring firmware-upgrading features..."
        return 0
    fi

    # - pre }}}

    if ((is_efi_booted)) ; then
        # refresh packages lists:
        fwupdmgr refresh -y --force # 1>/dev/null  # requires 300 KB of internet

        # show updates:
        #fwupdmgr get-updates # 1>/dev/null

        # see if we have already answered to not update firmwares
        if [[ -n "$conf_firmwares_updates_available" ]] && ! ((is_force)) ; then
            if [[ "$conf_firmwares_updates_available" = "never" ]] ; then
                el_info "You selected to never ask for firmware updates again, ignoring..."
                el_info "If you want to update firmwares, run the command: sudo $(basename $0) --upgrade-firmwares --force"
                return 0
            fi

            updates_list="$( fwupdmgr get-updates -y --force | grep "^Update Version:" | sort -u | tr '\n' ' ' | sort -u )"

            # our updates available is the same as the one found when we answered to not update firmwares
            if [[ "${updates_list}" = "$conf_firmwares_updates_available" ]] ; then
                el_info "You selected to not upgrade firmwares the last time we asked you for this, for this number of updates, ignoring..."
                el_info "If you want to update firmwares, run the command: sudo $(basename $0) --upgrade-firmwares --force"
                return 0
            fi
        fi


        if LC_ALL="$EL_LC_EN" fwupdmgr get-updates -y --force | grep -qsE "(^Update Name:|New version:)" ; then

            el_info "Firmware updates found:\n$( fwupdmgr get-updates | grep "^Update Version:" | sed -e 's|^Update Version:||g' )"

            # notify
            $guitool --info --text="$( eval_gettext "Firmware updates are available for your computer." )" 1>/dev/null 2>&1

            # display updates
            while read -ru 3 line
            do
                [[ -z "$line" ]] && continue
                case "$line" in
                    "Update Version:"*)
                        echo -e "\n\n${line}"
                        continue
                        ;;
                        "Update Name:"*)
                        echo "$line"
                        continue
                        ;;
                    "Update Description"*)
                        line="${line#Update Description:}"
                        read -r line <<< "$line"

                        echo -e "\n        ${line}"
                        ;;
                    "Update"*|"GUID:"*|"ID:"*)
                        continue
                        ;;
                    *)
                        echo "        $line"
                        ;;
                esac
            done 3<<< "$( LC_ALL="$EL_LC_EN" fwupdmgr get-updates -y --force )" | $guitool --height=400 --text-info --cancel-label="Done" --title="$( eval_gettext "Firmware updates available:" )" 1>/dev/null 2>&1


            local fw_warning_text choice
            fw_warning_text="$( eval_gettext "Firmware and BIOS updates are available for your computer.

WARNING: Updating your BIOS/firmware is not always recommended unless you are resolving specific hardware problems. While firmware updates can fix bugs, they can also introduce new regressions or issues (for example, webcams, Wi-Fi, or audio devices may stop functioning).

Select how you would like to proceed:" )"

            if [[ -n "$DISPLAY" ]] && command -v yad &>/dev/null; then
                $yad --title="$( eval_gettext "Firmware & BIOS Updates" )" \
                    --text="$fw_warning_text" --width=520 --text-align=left \
                    --button="$( eval_gettext "Install Updates" ):0" \
                    --button="$( eval_gettext "Ignore for Now" ):1" \
                    --button="$( eval_gettext "Skip this Update" ):2" \
                    --button="$( eval_gettext "Never Ask Again" ):3"
                choice=$?
            else
                echo -e "\n*** $( eval_gettext "Firmware & BIOS Updates" ) ***"
                echo -e "$fw_warning_text\n"
                echo "1) $( eval_gettext "Install Updates" )"
                echo "2) $( eval_gettext "Ignore for Now" )"
                echo "3) $( eval_gettext "Skip this Update" )"
                echo "4) $( eval_gettext "Never Ask Again" )"
                read -p "$( eval_gettext "Enter choice [1-4]: " )" opt
                case "$opt" in
                    1) choice=0 ;;
                    2) choice=1 ;;
                    3) choice=2 ;;
                    4) choice=3 ;;
                    *) choice=1 ;;
                esac
            fi

            case "$choice" in
                0) # Install Updates
                    if ! LC_ALL=C acpi -a 2>/dev/null | grep -qs "on-line" && laptop-detect ; then
                        $guitool --warning --text="$( eval_gettext "Important: Your system is not plugged in. Connect it before proceeding." )" 1>/dev/null 2>&1
                    fi

                    urxvt -e bash -c "COLUMNS=80 fwupdmgr -y --no-reboot-check update ; echo ; echo ; echo -e \"Upgrade DONE\nYou can close the terminal\" ; sleep 60 " 1>/dev/null
                    ;;
                1) # Ignore for Now
                    el_info "Skipping firmware updates for now."
                    ;;
                2) # Skip this Update (until next new firmware release)
                    updates_list="$( fwupdmgr get-updates -y --force | grep "^Update Version:" | sort -u | tr '\n' ' ' | sort -u )"
                    conf_firmwares_updates_available="$updates_list"
                    el_config_save "conf_firmwares_updates_available"
                    el_info "Saved choice to skip this specific firmware update."
                    ;;
                3) # Never Ask Again
                    conf_firmwares_updates_available="never"
                    el_config_save "conf_firmwares_updates_available"
                    el_info "Saved choice to never check or ask for firmware updates again."
                    ;;
            esac

        fi
    else
        el_info "Firmware upgrades requires UEFI, ignoring..."
    fi

}


# improved and much more reliable updater (will still works even if apt is broken or repos changed etc)
update_upgrader_fast(){
    if el_package_upgrade_fast 480 normal "elive-upgrader" ; then
        el_debug "TOOL UPDATED"
    fi

}
# old version, deprecated, less reliable, do not use it
#update_upgrader(){
    #if el_package_update_last_version -c "elive-upgrader" ; then
        ## update packages lists
        #if ! apt_get update -q=2 ; then
            #apt_get update -q=2
        #fi

        ## wait unlock
        #apt_get check 1>/dev/null

        ## verify apt status
        #if apt_get -y -f install -q=2 ; then
            #if ! bash -c "unset TERM DISPLAY ; export DEBIAN_FRONTEND=noninteractive ; apt-get install -o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" -q -y --force-yes elive-upgrader" ; then
                #el_error "problem upgrading elive-upgrader: $(apt-get install -y elive-upgrader 2>&1 )"
                #exit 1
            #fi
        #else
            ## apt status is wrong, force manual update of elive-upgrader
            #el_warning "problem with apt-get -y -f install: $(apt-get -y -f install 2>&1 ) : Trying to update elive-ugprader anyways with dpkg -x"

            #apt_get clean
            #apt_get update -q=2
            #apt_get install -d -y elive-upgrader

            #dpkg -i "$( find /var/cache/apt/archives/ -type f -iname elive-upgrader_'*'deb | sort -V | tail -1 )"
        #fi

    #else
        #el_debug "no new version of elive-upgrader found"
    #fi

    ## check apt status no matter what
    #if ! apt_get -y -f install -q=2 ; then
        #apt_get clean
        #apt_get update -q=2
        #apt_get dist-upgrade -y --force-yes

        #if ! apt_get -y -f install ; then
            #$guitool --error --text="$( eval_gettext "Seems like you have a broken state of your packages. Check our Elive Forums for a solution if you are unable to solve it yourself. Showing the result of the command:" ) apug"
            #el_error "Problem with apt-get -y -f install (reported): $(apt-get -y -f install 2>&1 )"
            #exit 1
        #fi
    #fi

    #exit 0
#}

main(){
    if [[ "$1" = "--enable-distro-upgrade" ]] ; then
        /usr/lib/elive-upgrader/debian-upgrader --enable-boot-upgrade "$2"
        exit $?
    fi

    if [[ "$1" = "--cancel-distro-upgrade" ]] ; then
        /usr/lib/elive-upgrader/debian-upgrader --cancel
        exit $?
    fi

    if [[ "$1" = "--distro-upgrade-status" ]] ; then
        /usr/lib/elive-upgrader/debian-upgrader --status
        exit $?
    fi

    # pre {{{
    version_elive="$( cat "/etc/elive-version" | grep "elive-version:" | awk '{print $2}' )"
    read -r version_elive <<< "$version_elive"

    hooks_d="/usr/lib/elive-upgrader/hooks"

    # }}}
    # never run on live mode {{{
    # managed already from the main script
    #if grep -qs "boot=live" /proc/cmdline ; then
        #exit
    #fi

    # }}}

    el_config_get

    # options
    for arg in "$@"
    do
        case "$arg" in
            --noaptupdate|--no-aptupdate)
                is_update_ignored=1
                ;;
            --ping)
                echo "pong"
                exit
                ;;
            --force)
                is_force=1
                ;;
            --betatest)
                is_betatester=1
                touch /tmp/.elive-upgrader-betatest
                ;;
            -h|--help)
                show_help
                exit 1
                ;;
        esac
    done

    for arg in "$@"
    do
        case "$arg" in
            #--delayed)
                #is_delayed=1
                #shift
                #;;
            --update|--update-tool)
                # TODO: delete the deprecated first paramter "--update" in the future
                #update_upgrader
                update_upgrader_fast
                ;;
            --hooks-root-pre)
                hooks_root_pre
                ;;
            --hooks-root-post)
                hooks_root_post
                ;;
            --upgrade)
                upgrade_system
                ;;
            --updates-available)
                updates_available_show
                ;;
            --upgrade-firmwares|--upgrade-firmware)
                upgrade_firmwares
                ;;
            --fix)
                apt_fixes
                ;;
        esac
    done

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
