#!/bin/bash
#
# Copyright (C) MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file MOXA-SOFTWARE-NOTICE for details.
#
# Authors:
# 	2021	Wes Huang	<Wes.Huang@moxa.com>

export GENERAL_VARIABLES="/lib/moxa-system-manager/general_variables"
export GENERAL_FUNCTIONS="/lib/moxa-system-manager/general_functions"
if [ -f "${GENERAL_VARIABLES}" ]; then
	source "${GENERAL_VARIABLES}"
fi
if [ -f "${GENERAL_FUNCTIONS}" ]; then
	source "${GENERAL_FUNCTIONS}"
fi

CHECK_HOOKS_DIR="/etc/moxa-system-manager/check-hooks.d/"

main() {
	local hook
	local ret_val
	local restore="0"
	local state

	_log_msg "debug" "${0}, ${FUNCNAME[0]}"
	_log_msg "debug" "CHECK_HOOKS_DIR=${CHECK_HOOKS_DIR}"

	state=$(mx-system-mgmt --system-failback state --value)
	case "${state}" in
	"${_STATE_ENABLED}")
		return 0
		;;
	"${_STATE_BOOTING}")
		for hook in "${CHECK_HOOKS_DIR}"*; do
			_log_msg "info" "Execute the check hook program: ${hook}"
			if [ -f "${hook}" ]; then
				${hook}
				ret_val="${?}"
				if [ ${ret_val} -eq 0 ]; then
					_log_msg "info" "The result of ${hook} is PASS."
					continue
				else
					_log_msg "warn" "The result of ${hook} is FAILED."
					restore=1
					break
				fi
			else
				_log_msg "warn" "The ${hook} file is not exist."
			fi
		done
		;;
	"${_STATE_RECOVERY}")
		restore=1
		;;
	*)
		_log_msg "warn" "Unknown return value"
		;;
	esac

	if [ "${restore}" == "1" ]; then
		_log_msg "info" "*************************************"
		_log_msg "info" "*** Restore the system by replica ***"
		_log_msg "info" "*************************************"
		mx-system-mgmt -S restore -y
		reboot
	else
		mx-system-mgmt -S disable -y
	fi
}

main

exit 0
