#!/usr/bin/sh

# A helper script to run apt-get noninteractively with the right settings.
# Run as one of:
#   run-apt-get update
#   run-apt-get upgrade-package packagename
#   run-apt-get upgrade-all

set -e

DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND

options="-o DPkg::Options::=--force-confdef -o DPkg::Options::=--force-confold -o DPkgPM::Progress=0"

action="$1"
shift

. /etc/os-release
case "$ID:$VERSION_ID" in
    raspbian:10) ;;
    raspbian:11) ;;
    raspbian:12) ;;

    *)
        echo "Automatic updates not officially supported for OS $ID:$VERSION_ID ($PRETTY_NAME)" >&2
        echo " .. but I'll go ahead and try it anyway .." >&2
        ;;
esac

case "$action" in
    update)
        dpkg --configure -a --force-confdef --force-confold || true
        apt-get -q -y $options update
        ;;

    upgrade-package)
        for package in "$@"
        do
            case "$package" in
                [a-zA-Z]*) ;;
                *) echo "bad package name: $package" >&2; exit 2 ;;
            esac
        done

        dpkg --configure -a --force-confdef --force-confold || true
        apt-get -q -y $options -f install || true
        apt-get -q -y $options install "$@" || exit 1
        apt-get -q $options clean || true
        ;;

    upgrade-all)
        dpkg --configure -a --force-confdef --force-confold || true
        apt-get -q -y $options -f install || true
        apt-get -q -y $options dist-upgrade || exit 1
        apt-get -q -y $options clean || true
        ;;

    *)
        echo "Unhandled action: $action"
        exit 1
        ;;
esac

exit 0
