#!/bin/sh
#===============================================================================
#
#  reboot_safe
#
#  Copyright (C) 2022 by Digi International Inc.
#  All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License version 2 as published by
#  the Free Software Foundation.
#
#
#  !Description: safe reboot script
#
#===============================================================================

scriptname="$(basename "$(readlink -f "${0}")")"
reboot_safe="$(find /sys/devices/ -name reboot_safe 2>/dev/null)"

# Default timeout 30s
TOUT="30"
UNLOCK_STR="CTRU"

usage() {
	printf "\nInitiates a reboot of the system and programs the MCA"
	printf "\nto force an immediate reset after a configured timeout."
	printf "\nThis assures the system will reset even if the"
	printf "\nsystem hangs during regular reboot process."
	printf "\nUsage: %s [OPTIONS]\n
	-t      timeout value in seconds (30 seconds by default)
	-h      Show this help
	\n" "${scriptname}"
}

while getopts "t:h" c; do
	case "${c}" in
		h) usage; exit;;
		t) TOUT=${OPTARG};;
	esac
done

if [ -f "${reboot_safe}" ]; then
	# Configure the MCA to reboot after ${TOUT} seconds
	echo "${UNLOCK_STR}${TOUT}" > "${reboot_safe}"
else
	printf "\nSafe reboot operation not supported. Proceeding with a regular reboot\n\n"
	exec reboot
fi
