#!/bin/bash

set -euo pipefail

## This is a quick hack to put a OOBE-gold-image version of the OS on the other slot and mark it active for next reboot,
## so we can test the flow of then updating from it to a day-1 update.

# Usage:
#   steamos-prepare-oobe-test [--factory-reset]
#   reboot
#
# Pass `--factory-reset` to also factory reset your device at the same time.


# The URL to query to determine what OOBE image to grab
if [[ "$(strings /proc/device-tree/model)" == SM8650* ]]; then
    OOBE_IMAGE_VER_URL="https://steamdeck-images.steamos.cloud/vr/latest-oobe-test-image.txt"
elif [[ "Valve Fremont" == "$(cat /sys/class/dmi/id/sys_vendor) $(cat /sys/class/dmi/id/product_name)" ]]; then
    # Fremont uses steamdeck image for now
    OOBE_IMAGE_VER_URL="https://steamdeck-images.steamos.cloud/steamdeck/latest-oobe-test-image.txt"
else
    OOBE_IMAGE_VER_URL="https://steamdeck-images.steamos.cloud/steamdeck/latest-oobe-test-image.txt"
fi


_log() { printf >&2 "[$1] %s\n" "${*:2}"; }
log() { _log - "$*"; }
cmd() { _log + "${*@Q}"; "$@"; }
die() { _log '!' "Fatal: $*"; exit 1; }

# Elevate
if [[ $EUID -ne 0 ]]; then
    log "Elevating to root"
    cmd exec pkexec --disable-internal-agent "$0" "$@"
fi

# Args
arg_factory_reset=
if [[ $# -eq 1 && $1 = "--factory-reset" ]]; then
    arg_factory_reset=1
elif [[ $# -ne 0 ]]; then
    die "Usage: $(basename -- "$0") [--factory-reset]"
fi

# Query version
log "Querying available OOBE test image version"
url=$(cmd curl --netrc -L "$OOBE_IMAGE_VER_URL" | grep -v '^#')

log "Target OOBE image: $url"

## Do the install
log "Installing '$url' to other slot"

cmd atomupd-manager custom-update "$url" || die "Install failed, see above."

if [[ -n $arg_factory_reset ]]; then
    log "--factory-reset specified, requesting factory reset on next boot"
    cmd steamos-factory-reset-config
fi

log "Other slot has been updated to $url and ready to be used as a OOBE image test"
log
log "  Run \`reboot\` to boot into the OOBE, which will perform a day one update."
log
log "  To abort rebooting into the OOBE and retain the current update, run:"
log "    sudo steamos-bootconf set-mode reboot"
