#!/bin/bash

. /etc/rc.d/efw_lib.sh

UPGRADED=/etc/upgrade/upgrade.d
PRE_HOOKS=/etc/upgrade/pre-upgrade.d
LOG="/var/efw/product/openfw-updates.log"
PIDFILE="/var/run/openfw-update.pid"
UPDATE_LIST_FILE="/var/cache/en/update_list"

# Show command output in interactive SSH sessions and keep the same output in
# the log used by the web interface. Web requests are redirected to the log by
# updates-system.cgi, so their output is not sent back in the HTTP response.
if [ -t 1 ]; then
    exec > >(tee -a "$LOG") 2>&1
else
    exec >> "$LOG" 2>&1
fi

loadSettings /var/efw/main/settings

function setupchannels() {
    smart channel --remove-all -y > /dev/null 2>&1
    smart channel --add openfw \
        baseurl="http://repo.openfw.com.br" \
        type=rpm-md -y > /dev/null 2>&1
}

function sync_update_cache() {
    local pending_count="$1"

    if [ "$pending_count" -gt 0 ]; then
        mkdir -p "$(dirname "$UPDATE_LIST_FILE")"
        printf '3\n' > "$UPDATE_LIST_FILE"
    else
        rm -f "$UPDATE_LIST_FILE"
    fi
}

function check_updates() {
    local output raw_output smart_status pending_count

    smart update > /dev/null 2>&1
    raw_output=$(smart newer 2>&1)
    smart_status=$?
    output=$(printf '%s\n' "$raw_output" | sed 's/\r//g; s/\[#*\]//g')
    printf '%s\n' "$output"

    if [ "$smart_status" -eq 2 ]; then
        # smart returns 2 when there are no interesting upgrades.
        pending_count=0
    elif [ "$smart_status" -eq 0 ]; then
        pending_count=$(printf '%s\n' "$output" | awk -F '|' '
            NF == 5 {
                priority = $5
                gsub(/^[[:space:]]+|[[:space:]]+$/, "", priority)
                if (priority ~ /^[0-9]+$/) count++
            }
            END { print count + 0 }
        ')
    else
        echo "!!! ERROR: Unable to determine pending updates; update cache left unchanged."
        return "$smart_status"
    fi

    sync_update_cache "$pending_count"
}

function start_upgrade() {
    local PACKAGES="$@"

    echo "+++ Running pre-upgrade hooks..."
    [ -d "${PRE_HOOKS}" ] && run-parts --report ${PRE_HOOKS}

    if [ -n "${PACKAGES}" ]; then
        echo "+++ Analyzing selected packages: ${PACKAGES}"

        local TO_UPGRADE=""
        local TO_INSTALL=""

        # Separate installed packages from new ones (including renamed packages)
        for pkg in ${PACKAGES}; do
            if rpm -q "$pkg" >/dev/null 2>&1; then
                TO_UPGRADE="$TO_UPGRADE $pkg"
            else
                TO_INSTALL="$TO_INSTALL $pkg"
            fi
        done

        if [ -n "$TO_UPGRADE" ]; then
            echo "+++ Upgrading installed packages: ${TO_UPGRADE}"
            smart upgrade -y ${TO_UPGRADE}
        fi

        if [ -n "$TO_INSTALL" ]; then
            echo "+++ Installing/Fallback for packages (new or renamed): ${TO_INSTALL}"
            smart install -y ${TO_INSTALL}
        fi
    else
        echo "+++ Starting full system upgrade..."
        smart upgrade -y
    fi

    if [ $? -eq 0 ]; then
        echo "+++ Running post-upgrade hooks..."
        [ -d "${UPGRADED}" ] && run-parts --report ${UPGRADED}
        # Recheck after a partial upgrade so remaining updates keep the cache.
        check_updates || echo "!!! WARNING: Upgrade finished, but the update cache could not be refreshed."
        echo "+++ Upgrade process finished successfully."
    else
        echo "!!! ERROR: System upgrade failed."
    fi
}

ACTION="$1"

case "$ACTION" in
    update)
        echo $$ > "$PIDFILE"
        trap "rm -f '$PIDFILE'; exit" INT TERM EXIT
        > "$LOG"
        setupchannels
        check_updates
        ;;
    upgrade)
        echo $$ > "$PIDFILE"
        trap "rm -f '$PIDFILE'; exit" INT TERM EXIT
        shift
        start_upgrade "$@"
        ;;
    checkupdates)
        check_updates
        ;;
    *)
        echo "Usage: $0 {update|upgrade|checkupdates} [package1 package2 ...]"
        exit 1
        ;;
esac
