#!/bin/sh
# Upgrade the simulator in place, from packages on the web.
#
# Started as root by sim_upgrade.service, which the web UI's Upgrade tab triggers. It is
# deliberately not run by the web server itself: an upgrade needs root, takes minutes,
# and install64.sh restarts lighttpd - which would kill the very request that started it.
# So the page writes what it wants into the request file, starts the unit, and then just
# watches this log.
#
# Request file, written by upgrade.py, one key per line, only the keys to act on:
#
#   px4=<url>          PX4 firmware: a sim bundle tar.gz, or the directory holding it
#   model=<url>        flight-mechanics model package
#   simulator=<url>    box payload: scripts, services, web UI
#   reboot=yes         reboot when everything else succeeded
#
# A URL may name the artefact itself or the directory it sits in; either way SHA256SUMS
# must sit beside it, and nothing is installed that does not match it.

INSTALL=/opt/px4
REQUEST=$INSTALL/upgrade.request
LOG=$INSTALL/upgrade.log
WORK=/tmp/sim-upgrade.$$

log() { echo "$(date '+%H:%M:%S') $*" >> "$LOG"; }
# The request is dropped on failure as well: what was attempted is in the log, and a
# stale request must not be re-applied if the unit is ever started by hand.
die() { log "FAILED: $*"; log "--- upgrade aborted ---"; rm -rf "$WORK"; rm -f "$REQUEST"; exit 1; }

: > "$LOG"
chmod a+r "$LOG"
log "--- upgrade started ---"

[ -f "$REQUEST" ] || die "no request file"
mkdir -p "$WORK" || die "cannot create $WORK"

# The request file is written by the web server, so treat every value in it as input from
# outside: read it with `read`, never source it, and keep each URL inside quotes so no
# shell ever gets a chance to interpret it.
px4_url=
model_url=
sim_url=
do_reboot=no

while IFS='=' read -r key value; do
	case "$key" in
		px4)       px4_url=$value ;;
		model)     model_url=$value ;;
		simulator) sim_url=$value ;;
		reboot)    [ "$value" = yes ] && do_reboot=yes ;;
		''|\#*)    ;;
		*)         log "ignoring unknown request key '$key'" ;;
	esac
done < "$REQUEST"

# Only plain http(s) URLs built from characters that are legal in one. Anything else is
# refused rather than cleaned up, because a URL is not something to guess at.
check_url() {
	case "$1" in
		http://*|https://*) ;;
		*) die "'$1' is not an http(s) URL" ;;
	esac
	case "$1" in
		*[!A-Za-z0-9._~:/?\#@!\&\*+,=%-]*) die "URL contains a character that does not belong in a package address" ;;
	esac
}

# Fetch an artefact and refuse to install it unless it matches the SHA256SUMS published
# beside it. $1 = url (file or directory), $2 = a pattern the file name must match,
# $3 = where to put it. Prints the resolved file name.
fetch_verified() {
	url=$1; want_pattern=$2; outdir=$3

	case "$url" in
		*/) dir=${url%/}; name= ;;
		*)  dir=$(dirname "$url"); name=$(basename "$url") ;;
	esac

	curl -fsSL -o "$outdir/SHA256SUMS" "$dir/SHA256SUMS" \
		|| die "no SHA256SUMS at $dir/ - wrong address, or an incomplete publish"

	if [ -z "$name" ]; then
		# A directory was given, so take the archive out of the checksum list rather
		# than guessing the file name.
		name=$(awk '{ sub(/^\*/,"",$2); print $2 }' "$outdir/SHA256SUMS" \
			| grep -E "$want_pattern" | head -1)
		[ -n "$name" ] || die "no file matching $want_pattern listed at $dir/"
	fi

	log "    downloading $name"
	curl -fsSL -o "$outdir/$name" "$dir/$name" || die "cannot download $dir/$name"

	want=$(awk -v f="$name" '{ sub(/^\*/,"",$2) } $2 == f { print $1 }' "$outdir/SHA256SUMS" | head -1)
	[ -n "$want" ] || die "SHA256SUMS has no entry for $name"
	got=$(sha256sum < "$outdir/$name" | cut -d' ' -f1)
	[ "$want" = "$got" ] || die "checksum mismatch for $name (published $want, got $got)"
	log "    $name verified"

	# The MANIFEST says what this package is, and the Upgrade tab shows it. For the model
	# and the payload it lives beside the archive on the server rather than inside it, so
	# fetch it too. Nothing below writes to stdout: the caller captures that.
	if awk '{ sub(/^\*/,"",$2) } $2 == "MANIFEST" { found=1 } END { exit !found }' \
			"$outdir/SHA256SUMS"; then
		if curl -fsSL -o "$outdir/MANIFEST.published" "$dir/MANIFEST"; then
			want=$(awk '{ sub(/^\*/,"",$2) } $2 == "MANIFEST" { print $1 }' "$outdir/SHA256SUMS" | head -1)
			got=$(sha256sum < "$outdir/MANIFEST.published" | cut -d' ' -f1)
			[ "$want" = "$got" ] || die "checksum mismatch for MANIFEST"
		fi
	fi

	echo "$name"
}

rc=0

# ---------------------------------------------------------------------------
# PX4 firmware. Only bin/ and etc/ move; the rest of the box is untouched.
# ---------------------------------------------------------------------------
if [ -n "$px4_url" ]; then
	check_url "$px4_url"
	log "PX4 firmware from $px4_url"
	mkdir -p "$WORK/px4"
	name=$(fetch_verified "$px4_url" '\.tar\.gz$' "$WORK/px4") || exit 1
	tar xzf "$WORK/px4/$name" -C "$WORK/px4" || die "cannot unpack $name"
	[ -f "$WORK/px4/MANIFEST" ] || die "$name has no MANIFEST - is it a PX4 sim bundle?"

	arch=$(sed -n 's/^arch=//p' "$WORK/px4/MANIFEST" | head -1)
	[ -z "$arch" ] || [ "$arch" = arm64 ] || die "bundle is $arch, this box needs arm64"

	systemctl stop sim_px4
	rm -rf "$INSTALL/bin"
	mkdir -p "$INSTALL/bin"
	cp -a "$WORK/px4/bin/." "$INSTALL/bin/" || die "cannot install the firmware"
	cp -a "$WORK/px4/etc/." "$INSTALL/etc/" || die "cannot install the firmware config"
	cp -f "$WORK/px4/MANIFEST" "$INSTALL/MANIFEST"
	[ -d "$WORK/px4/params" ] && cp -a "$WORK/px4/params" "$INSTALL/etc/"
	chmod -R o+rx "$INSTALL/bin"
	systemctl start sim_px4
	log "PX4 now $(sed -n 's/^px4_version=//p' "$INSTALL/MANIFEST" | head -1)"
fi

# ---------------------------------------------------------------------------
# Flight-mechanics model: one binary.
# ---------------------------------------------------------------------------
if [ -n "$model_url" ]; then
	check_url "$model_url"
	log "model from $model_url"
	mkdir -p "$WORK/model"
	name=$(fetch_verified "$model_url" '\.tar\.gz$' "$WORK/model") || exit 1
	tar xzf "$WORK/model/$name" -C "$WORK/model" || die "cannot unpack $name"

	binary=$(find "$WORK/model" -name 'songbird_sim_px4_udp' -type f | head -1)
	[ -n "$binary" ] || die "$name holds no songbird_sim_px4_udp - is it the model package?"

	systemctl stop sim_songbird
	cp -f "$binary" "$INSTALL/songbird_sim_px4_udp" || die "cannot install the model"
	chmod 755 "$INSTALL/songbird_sim_px4_udp"
	[ -f "$WORK/model/MANIFEST.published" ] && cp -f "$WORK/model/MANIFEST.published" "$INSTALL/MANIFEST.model"
	systemctl start sim_songbird
	log "model installed"
fi

# ---------------------------------------------------------------------------
# The box itself: scripts, services, web UI. install64.sh does the work, and with no
# rpi/bin staged it leaves the installed firmware alone.
# ---------------------------------------------------------------------------
if [ -n "$sim_url" ]; then
	check_url "$sim_url"
	log "simulator from $sim_url"
	mkdir -p "$WORK/sim"
	name=$(fetch_verified "$sim_url" '\.tar\.gz$' "$WORK/sim") || exit 1
	mkdir -p "$WORK/payload"
	tar xzf "$WORK/sim/$name" -C "$WORK/payload" || die "cannot unpack $name"
	[ -f "$WORK/payload/install64.sh" ] || die "$name holds no install64.sh - is it the box payload?"

	[ -f "$WORK/sim/MANIFEST.published" ] && cp -f "$WORK/sim/MANIFEST.published" "$INSTALL/MANIFEST.simulator"

	log "    running install64.sh (this takes a few minutes)"
	chmod +x "$WORK/payload/install64.sh"
	# Its output belongs in this log: it is the only record of what the upgrade did, and
	# the page shows it. It restarts lighttpd near the end, which is survivable only
	# because this runs detached from the web request.
	( cd "$WORK/payload" && ./install64.sh ) >> "$LOG" 2>&1 || rc=1
	[ "$rc" = 0 ] || die "install64.sh reported a problem - see above"
	log "simulator installed"
fi

if [ -z "$px4_url" ] && [ -z "$model_url" ] && [ -z "$sim_url" ]; then
	die "nothing to do - no component was given"
fi

rm -rf "$WORK"
rm -f "$REQUEST"
log "--- upgrade finished ---"

if [ "$do_reboot" = yes ]; then
	# In the foreground, not backgrounded. This runs as a Type=oneshot unit with the
	# default KillMode=control-group, so anything still in the cgroup is killed the
	# moment the main process exits - a `( sleep 5; systemctl reboot ) &` was killed
	# before it ever fired, and the box quietly stayed up.
	log "rebooting in 5 s, as requested"
	sleep 5
	systemctl reboot
fi

exit 0
