#!/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.

# The exact OS image version that is a test-gold-image to use
OOBE_IMAGE_VER=20211122.8
# Where to get it, since we'll ask rauc directly
OOBE_IMAGE_URL="http://steamdeck-images.steamos.cloud/steamdeck/$OOBE_IMAGE_VER/steamdeck-$OOBE_IMAGE_VER-snapshot.raucb"

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

# We cannot install the same version on both slots. If we are somehow in this OOBE image, refuse.
osver=$(source /etc/os-release && printf "%s" "$BUILD_ID")

[[ -n $osver ]] || die "Couldn't determine OS version"
[[ $osver != "$OOBE_IMAGE_VER" ]] || die "Booted OS is already the configured OOBE test image"

# First, check if the other slot is already configured to this.  This is a dumb hack, the rauc slot-status isn't working
# right as I write this so we cannot check if this is a partial install.  Gross.
other=$(sudo steamos-chroot --partset other -- cat /usr/lib/oobe-test-flag 2>/dev/null) || true
if [[ -n $other && $other = "$OOBE_IMAGE_VER" ]]; then
  log "Other slot is already on the correct version ($OOBE_IMAGE_VER) and ready to be used for OOBE image testing"
  log "Marking other slot for next boot."
  sudo touch /run/steamos/reboot-other
  exit 0
fi

## Need to do the install
log "Installing '$OOBE_IMAGE_URL' to other slot"

# Workaround this rauc issue that needs a lot of inodes in /tmp -- the normal atomupd client has this workaround
# too. Nice.
sudo mount -o remount,size=100%,nr_inodes=1g /tmp
# Install
cmd sudo rauc install "$OOBE_IMAGE_URL"

# Set the flag with a dumb hack so we know the partition is ready to be used for this.  This is only working around our
# rauc slot-status query not being right, so we know it wasn't half-installed. The image itself that we installed is a
# gold-only image, that has a newer image available to update to.
log "Install successful, marking slot"
sudo tune2fs -O ^read-only /dev/disk/by-partsets/other/rootfs &>/dev/null
echo "$OOBE_IMAGE_VER" | sudo steamos-chroot --partset other -- bash -c "mount -o remount,rw / && tee /usr/lib/oobe-test-flag" >/dev/null
sudo tune2fs -O read-only /dev/disk/by-partsets/other/rootfs &>/dev/null
sudo sync

log "Other slot has been updated to version $OOBE_IMAGE_VER and ready to be used as a OOBE image test"
# rauc install automatically marks the other spot for next build, so we're good
