#!/usr/bin/env bash

set -euo pipefail

ALLOW_REBOOT=
NO_CONFIRM=
NODE_EXPORTER_METRICS_PATH=

while [[ $# -gt 0 ]]; do
	case $1 in
		--allow-reboot)
			ALLOW_REBOOT=1
			shift
		;;
		--no-confirm)
			NO_CONFIRM=1
			shift
		;;
		--node-exporter-metrics-path)
			NODE_EXPORTER_METRICS_PATH=$2
			shift
			shift
		;;
		*)
			echo "Unknown option $1"
			exit 1
		;;
	esac
done

HYDRA_JOB_URL="https://hydra.clerie.de/job/nixfiles/nixfiles/nixosConfigurations.${HOSTNAME}/latest-finished"

echo "Fetching job output from ${HYDRA_JOB_URL}"
STORE_PATH="$(curl --fail -s -L -H "Accept: application/json" "${HYDRA_JOB_URL}" | jq -r ".buildoutputs.out.path")"

if [[ -z $NO_CONFIRM ]]; then
	echo ""
	echo "  ! WARNING !"
	echo ""
	echo "  You are about to upgrade ${HOSTNAME} to ${STORE_PATH}."
	echo "  This can be an older version than currently running on this system."
	echo ""
	read -e -r -p "Continue?" confirm
	echo "$confirm" > /dev/null
fi

echo "Download ${STORE_PATH}"
nix copy --from "https://nix-cache.clerie.de" "${STORE_PATH}"

echo "Add to system profile"
nix-env -p "/nix/var/nix/profiles/system" --set "${STORE_PATH}"

echo "Set as boot target"
/nix/var/nix/profiles/system/bin/switch-to-configuration boot

if [[ -n "$NODE_EXPORTER_METRICS_PATH" ]]; then
	echo "Write monitoring check data"
	echo "clerie_system_upgrade_last_check $(date +%s)" > "$NODE_EXPORTER_METRICS_PATH"
fi

BOOTED_SYSTEM_KERNEL="$(readlink /run/booted-system/{initrd,kernel,kernel-modules})"
ACTIVATING_SYSTEM_KERNEL="$(readlink /nix/var/nix/profiles/system/{initrd,kernel,kernel-modules})"

if [[ "$BOOTED_SYSTEM_KERNEL" != "$ACTIVATING_SYSTEM_KERNEL" ]]; then
	echo "Reboot is required"
	if [[ -n "$ALLOW_REBOOT" ]]; then
		echo "Rebooting system now"
		shutdown -r +1 "System update requires reboot"
	else
		echo "Automatic reboot not allowed (maybe use --allow-reboot next time)"
		echo "The system upgrade is staged, please reboot manually soon"
	fi
else
	echo "No reboot is required"
	echo "Activating system now"
	/nix/var/nix/profiles/system/bin/switch-to-configuration switch
fi

echo "Finished system upgrade"