#!/usr/bin/bash
set -euo pipefail

if [[ ${EUID} -ne 0 ]]; then
    echo "repogoon-update-channel must run as root" >&2
    exit 1
fi

operation=${1:-}
case "$operation" in
    stable|preview)
        ;;
    apply)
        ;;
    *)
        echo "usage: repogoon-update-channel stable|preview|apply" >&2
        exit 2
        ;;
esac

# Ask the system manager to start a separate root unit. Unlike a sudo child,
# that unit does not inherit repogoon.service's protected mount namespace.
if [[ $operation == stable || $operation == preview ]]; then
    channel=$operation
    exec /usr/bin/systemctl start --no-block "repogoon-update-channel@${channel}.service"
fi

status_directory=/run/repogoon-update
status_file=${status_directory}/update-status.json
if [[ -L $status_directory ]]; then
    echo "refusing symlinked update status directory" >&2
    exit 2
fi
/usr/bin/install -d -o root -g root -m 0755 "$status_directory"
temporary=$(/usr/bin/mktemp "${status_file}.tmp.XXXXXX")
/usr/bin/chmod 0644 "$temporary"
printf '%s\n' '{"schemaVersion":1,"command":"update-apply","state":"queued","phase":"queued","message":"Waiting for the privileged update worker","package":"","previousVersion":"","currentVersion":"","rollbackCommand":"","updatedAt":""}' > "$temporary"
/usr/bin/mv -f "$temporary" "$status_file"

worker_status=0
/usr/bin/systemctl start "repogoon-update-channel@apply.service" || worker_status=$?
if [[ ! -f $status_file ]] || [[ $(/usr/bin/stat --format=%s "$status_file") -gt 65536 ]]; then
    echo "update worker did not produce a bounded status document" >&2
    exit 2
fi
/usr/bin/cat "$status_file"
if [[ $worker_status -ne 0 ]] || ! /usr/bin/grep -Fq '"state":"succeeded"' "$status_file"; then
    exit 2
fi
