#!/bin/bash
set -eE

export LC_ALL=C
export LANG=C

if [ `whoami` != root ]; then
	set +x
	echo "============================"
	echo "Please run it under the root"
	echo "============================"
	set -x
	exit 1
fi

_opt_no_self_update=""
_opt_no_reboot=""
_opt_power_off=""
while test "$#" != 0; do
	case "$1" in
		--no-self-update) _opt_no_self_update=1;;
		--no-reboot) _opt_no_reboot=1;;
		--power-off) _opt_power_off=1;;
		*) echo "Usage: pikvm-update [--no-reboot] [--power-off]"; exit 1;;
	esac
	shift
done

set -x

function show_rw_msg() {
	set +x
	echo "=============================================================="
	echo "Please note that the filesystem now remain in Read-Write mode."
	echo "       A reboot is necessary to make it Read-Only again."
	echo "The reboot can be performed later using the 'reboot' command."
	echo "=============================================================="
	set -x
}
function on_error() {
	set +x
	echo "=============================================================="
	echo "      An unexpected error occurred during the update."
	echo "=============================================================="
	echo
	show_rw_msg
	set -x
}
trap on_error ERR

_yes="--noconfirm --ask=4 --overwrite \\*"
_remove_yes="--noconfirm --ask=4"

rw
pacman -Syy

if [ `pacman -S -u --print-format %n | grep -v pikvm-os-updater | wc -l` -eq 0 ]; then
	set +x
	echo "================================"
	echo "Your PiKVM is already up-to-date"
	echo "================================"
	set -x
	ro
	exit 0
fi

rm -rf /var/cache/pacman/pkg
mkdir -p /var/cache/pacman/pkg

if [ -z "$_opt_no_self_update" ]; then
	if [ `pacman -S --needed --print-format %n pikvm-os-updater | wc -l` -ne 0 ]; then
		pacman $_yes -S pikvm-os-updater
		_opts=--no-self-update
		if [ -n "$_opt_no_reboot" ]; then
			_opts="$_opts --no-reboot"
			trap - ERR
		fi
		pikvm-update $_opts
		exit $?
	fi
fi

if ! grep -q "^C.UTF-8 UTF-8" /etc/locale.gen; then
	# bsdtar: bsdtar: Failed to set default localeFailed to set default locale
	echo "C.UTF-8 UTF-8" >> /etc/locale.gen
	locale-gen || true
fi

for _pkg in rpi-eeprom rpi4-eeprom edid-decode; do
	if pacman -Q $_pkg >/dev/null 2>&1; then
		pacman $_remove_yes -R $_pkg
	fi
done

if ! pacman -Q raspberrypi-utils >/dev/null 2>&1; then
	pacman $_yes -Sdd raspberrypi-utils
fi

if pacman -Q python-periphery >/dev/null 2>&1; then
	# KVMD doesn't need this anymore
	pacman $_remove_yes -Rdd python-periphery
fi

if pacman -Q python-bcrypt >/dev/null 2>&1; then
	# Conflicts with kvmd, it needs manual removal for some reason
	# Also: https://gitlab.archlinux.org/pacman/pacman/-/issues/60
	pacman $_remove_yes -Rdd python-bcrypt
fi

if [[ "$(vercmp $(pacman -Q linux-firmware-pikvm | awk '{print $2}') 20251021-1)" -lt 0 ]]; then
	pacman $_remove_yes -Rdd linux-firmware-pikvm
	pacman $_yes -S linux-firmware-pikvm
fi
if ! pacman -Q linux-firmware-pikvm >/dev/null 2>&1; then
	pacman $_yes -S linux-firmware-pikvm
fi

# XXX: Don't do this because:
#   :: wpa_supplicant-pikvm-2:2.10-10 and kvmd-4.119-1 are in conflict. Remove kvmd? [y/N] 
#if ! pacman -Q wpa_supplicant-pikvm >/dev/null 2>&1; then
#	pacman $_yes -Sdd wpa_supplicant-pikvm
#fi

pacman $_yes -Su

if systemctl is-enabled -q tailscaled; then
	if [ -f /etc/default/tailscale ]; then
		source /etc/default/tailscale
	fi
	systemctl restart tailscaled
	tailscale up $TAILSCALE_FLAGS
fi

if ! kvmd -m >/dev/null 2>&1; then
	set +x
	echo "=================================================="
	echo "     During the update, something went wrong"
	echo " and the KVMD configuration was no longer valid."
	echo "             _____________________"
	echo "             !!! DO NOT REBOOT !!!"
	echo "             ---------------------"
	echo
	echo "  Please do following:"
    echo "  * Run 'kvmd -m' command to check the config."
	echo "  * Fix the error."
	echo "  * After that, run 'kvmd -m' again."
	echo "  * If you see a large and beautiful configuration"
    echo "    dump, you can run the 'reboot' command."
	echo "  * If you are unable to fix the error,"
	echo "  * please contact our online support chat:"
	echo "       __________________________________"
	echo "       >>> https://discord.gg/bpmXfz5 <<<"
	echo "       ----------------------------------"
	echo "=================================================="
	set -x
	exit 101
fi

if [ -n "$_opt_power_off" ]; then
    set +x
	echo "=============================================================="
	echo "      Power off requested. We will make it after 30 seconds."
	echo "            Press Ctrl+C if you don't want this."
	echo "=============================================================="
	echo
	show_rw_msg
	set -x
	sleep 30
	poweroff
elif [ -z "$_opt_no_reboot" ]; then
	set +x
	echo "=============================================================="
	echo "      Reboot required. We will make it after 30 seconds."
	echo "            Press Ctrl+C if you don't want this."
	echo "=============================================================="
	echo
	show_rw_msg
	set -x
	sleep 30
	reboot
else
	trap - ERR
	set +x
	echo "=============================================================="
	echo "        Reboot required. Please perform it manually."
	echo "=============================================================="
	echo
	show_rw_msg
	set -x
	exit 100
fi
