#!/bin/sh
set -eu

BOOT="/boot"
OTA="$BOOT/ota"
CYCLE_MARKER="/run/signage-cycle-complete"

mountpoint -q "$BOOT" || mount "$BOOT"

mkdir -p "$OTA"

if [ -f "$OTA/pending-root" ]; then
	echo "[OTA] Waiting for signage to complete a full playlist cycle..."
	while [ ! -f "$CYCLE_MARKER" ]; do
		sleep 5
	done
	echo "[OTA] Signage completed a full playlist cycle"
fi

rm -f "$OTA/rollback.flag"
rm -f "$OTA/pending-root"
rm -f "$OTA/previous-root"
rm -f "$OTA/attempted-root"
rm -f "$OTA/pending-label"
rm -f "$OTA/pending-partition"
rm -f "$OTA/staged-at"
rm -f "$OTA/boot-attempts"


if [ -f "$OTA/last-booted-root" ]; then
	cp "$OTA/last-booted-root" "$OTA/current-root"
fi

date -u +"%Y-%m-%dT%H:%M:%SZ" > "$OTA/last-good-boot"

sync
