#!/bin/bash

# This script can be used to reboot the Nyquist appliance

caller=$1

CAN_FW_LOCK=/run/lock/nyquist-can-fw.lock
exec 9>"$CAN_FW_LOCK"
if ! flock -n 9; then
	logger -t reboot_now "CAN firmware update is active; queuing reboot"
	if ! systemd-run --no-block --unit=nyquist-deferred-reboot \
		--service-type=oneshot /usr/bin/flock -w 900 "$CAN_FW_LOCK" \
		/bin/systemctl reboot; then
		logger -t reboot_now "Failed to queue deferred reboot"
		exit 1
	fi
	exit 0
fi

if [ "${caller}" != "button" ]; then
	sudo shutdown -r now
else
	systemctl --force reboot
fi
