#!/bin/sh
#===============================================================================
#
#  poweroff_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 power-off script
#
#===============================================================================

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

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

usage() {
	printf "\nInitiates a power-off on the system and programs the MCA"
	printf "\nto force an immediate power-off after a configured timeout."
	printf "\nThis assures the system will power off even if the"
	printf "\nsystem hangs during regular shut down 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 "${pwroff_safe}" ]; then
	# Configure the MCA to power off after ${TOUT} seconds
	echo "${UNLOCK_STR}${TOUT}" > "${pwroff_safe}"
else
	printf "\nSafe power-off operation not supported. Proceeding with a regular power-off\n\n"
	exec poweroff
fi
