#!/usr/bin/env bash
#
# install-disk.sh — install a variant to state/disk.raw with bootc, ready to
# boot with vm.sh.
#
#   install-disk.sh n1
#
# Destroys whatever was on the disk. That is the point: every case starts from
# a freshly installed machine, and reusing a disk across shapes is how a run
# ends up measuring the last run.
#
# --target-imgref is what makes the rest work. Without it the installed system
# would point at localhost/alloy-layertest, which resolves to nothing inside
# the guest, and no upgrade could ever be fetched. Pointing it at the host's
# registry is the same trick build-iso.sh --update-target plays for the ISO.
#
# No TPM, no encryption, unlike vmtest. This harness measures what rpm-ostree
# and bootc do to a layered package, and the encrypted path only adds ways for
# a run to fail for unrelated reasons.
set -euo pipefail

# shellcheck source=build/layertest/common.sh
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"

# shellcheck source=build/privilege.sh
. "$HERE/../privilege.sh"

MARK="${1:-}"
[ -n "$MARK" ] || die "usage: install-disk.sh <mark>   (n1 n2 n3 n4 r1 l1)"
privc podman image exists "$IMAGE:$MARK" || die "no image $IMAGE:$MARK; run build.sh"

# The firmware variables go with the disk. Leaving them behind boots the old
# disk's boot entries against a new install and lands at a grub prompt, which
# is the same lesson vmtest's README records.
rm -f "$STATE/disk.raw" "$STATE/OVMF_VARS.fd"
truncate -s 20G "$STATE/disk.raw"

say "installing $MARK to state/disk.raw"
privc podman run --rm --privileged --pid=host \
  --security-opt label=type:unconfined_t \
  -v /var/lib/containers:/var/lib/containers \
  -v /dev:/dev \
  -v "$STATE:/output" \
  "$IMAGE:$MARK" \
  bootc install to-disk --via-loopback --generic-image --filesystem ext4 \
    --target-imgref "$HOST_FROM_GUEST:$REGISTRY_PORT/alloy-layertest:latest" \
    /output/disk.raw

# The installed system will pull its upgrades from :latest, so :latest has to
# be the variant just installed or the first upgrade would be a surprise.
privc podman push --tls-verify=false "$IMAGE:$MARK" \
  "127.0.0.1:$REGISTRY_PORT/alloy-layertest:latest" >/dev/null 2>&1
say "installed $MARK, and pushed it as :latest"
