#!/usr/bin/env bash
# bluerune-unattended.service: an unattended install, as Omarchy's ISO does it. When a drive
# labelled `cidata` holds bluerune.json, bluerune-install installs from it without asking,
# then the machine restarts into the new system. Without one it does nothing, and the live
# session starts. It shows on the first console (the live session waits for it) and on the
# first serial port when the machine has one; each line it ends with starts
# "BLUERUNE-UNATTENDED:", for scripts reading the serial port (release/iso/test.sh).

serial=''
[[ $(cat /sys/class/tty/ttyS0/type 2>/dev/null) =~ ^[1-9] ]] && serial=/dev/ttyS0

say() {
    printf '%s\n' "$*"
    [[ -z $serial ]] || printf '%s\r\n' "$*" >"$serial"
}

udevadm settle --timeout=15 || true
drive=''
for label in cidata CIDATA; do
    [[ -e /dev/disk/by-label/$label ]] && { drive=/dev/disk/by-label/$label; break; }
done
[[ -n $drive ]] || exit 0

mnt=/run/bluerune-cidata
config=/run/bluerune-unattended.json
mkdir -p "$mnt"
mount -o ro "$drive" "$mnt" || { say "BLUERUNE-UNATTENDED: couldn't mount $drive"; exit 0; }
found=0
[[ -f $mnt/bluerune.json ]] && cp -- "$mnt/bluerune.json" "$config" && chmod 600 "$config" && found=1
umount "$mnt"
((found)) || exit 0

say "BlueRune: an unattended install, from bluerune.json on the cidata drive."
started=$SECONDS
if [[ -n $serial ]]; then
    bluerune-install --config "$config" --yes 2>&1 | tee "$serial"
    status=${PIPESTATUS[0]}
else
    bluerune-install --config "$config" --yes
    status=$?
fi
rm -f -- "$config"
if ((status == 0)); then
    say "BLUERUNE-UNATTENDED: installed in $((SECONDS - started)) s; restarting"
    sync
    systemctl reboot
else
    say "BLUERUNE-UNATTENDED: failed ($status); the log is /var/log/bluerune-install.log"
fi
