#!/usr/bin/env bash

print_help() {
    (>&2 cat <<EOF
Update packages.
Usage: $0 [-h|-?|--help]
           Print this help text and exit.
     - $0 <package-name...>
           Update the selected packages.
     - $0
           Update all packages.
EOF
)
}

update_package() {
    local pkg="$1"
    local before="$2"
    if [ -z "$before" ]; then
        local epkg=$(escape_string "$pkg")
        before=$(cat "$SSPT_SRC_DB_FILE" | egrep "^$pkg " | egrep -v -o "^$epkg ")
    fi
    exec_subcommand pkgcmd pull "$pkg"
    local after=$(exec_subcommand pkgcmd vesion "$pkg")

    if [ "$before" != "$after" ]; then
        exec_subcommand src-db reg "$pkg" "$after"

        return 1
    fi

    return 0
}
upgrade_package() {
    exec_subcommand configure "$1"
    exec_subcommand build "$1"
    exec_subcommand install "$1"
}
upgrade_pkgs() {
    for pkg in $(cat /tmp/upgrade_list); do
        upgrade_package "$pkg"
    done
    rm /tmp/upgrade_list
}

update_selection() {
    touch /tmp/upgrade-list

    for pkg in "${@[@]}"; do
        update_package "$pkg" ""
        if [ $? -ne 0 ]; then
            echo "$pkg" >> /tmp/upgrade_list
        fi
    done

    upgrade_pkgs
}

update_all() {
    touch /tmp/upgrade-list

    for pkg_and_ver in $(cat "$SSPT_SRC_DB_FILE"); do
        local pkg=$(echo "$pkg_and_ver" | egrep -o "^[A-Za-z0-9_\-\.]")
        local before=$(echo "$pkg_and_ver" | egrep -o "[A-Za-z0-9_\-\.]$")

        update_package "$pkg" "$before"
        if [ $? -ne 0 ]; then
            echo "$pkg" >> /tmp/upgrade_list
        fi
    done

    upgrade_pkgs
}

if [ $# -eq 0 ]; then
    update_all
    exit
fi

update_selection $@

