#!/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>

if [ -f "${GENERAL_VARIABLES}" ]; then
	source "${GENERAL_VARIABLES}"
fi
if [ -f "${GENERAL_FUNCTIONS}" ]; then
	source "${GENERAL_FUNCTIONS}"
fi

default_restore() {
	local state

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

	_question "${MSM_FLAG_YES}" "Would you like to restore the system to its default state? (y/N)"

	state=$(mx-system-mgmt --system-failback state --value)
	if [ "${state}" != "${_STATE_DISABLED}" ]; then
		_log_msg "info" "System failback has been enabled and the replica has been created on your system. Continue with restore will disable system failback and remove replica."
		_question "${MSM_FLAG_YES}" "Would you like to continue? (y/N)"
		mx-system-mgmt --system-failback disable -y
	fi

	# start to restore the system with default system status
	_restore "default_restore"
	_set_flag "default_restore"
	_log_msg "info" "System has been restored successfully. Reboot is required to take effect."
}

default_decommission() {
	local state

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

	_log_msg "info" "The decommissioning process will restore the system back to its factory defaults"
	_log_msg "info" "and remove all user files and system logs such that they are unrecoverable."
	_question "${MSM_FLAG_YES}" "The process may take a while depending on your system. Would you like to continue? (y/N)"

	state=$(mx-system-mgmt --system-failback state --value)
	if [ "${state}" != "${_STATE_DISABLED}" ]; then
		_log_msg "info" "System failback has been enabled and the replica has been created on your system. Continue with decommission will disable system failback and remove replica."
		_question "${MSM_FLAG_YES}" "Would you like to continue? (y/N)"
		mx-system-mgmt --system-failback disable -y
	fi

	# start to decommission the system with default system status
	_restore "default_restore"
	_set_flag "default_restore"
	touch "${DECOMMISSION_FLAG_FILE}"
	sync

	if [ "${BOOTLOADER_DECOMMISSION}" == "y" ]; then
		if [ "${SYS_ARCH}" == "x86_64" ]; then
			mx-bios-mgmt decommission -s -y &>/dev/null
		else
			mx-bootloader-mgmt decommission -s -y &>/dev/null
		fi
	fi
	_log_msg "info" "System has been restored successfully. Reboot is required to take effect and complete the decommissioning process."
}

main() {
	local sub_command="${1}"
	_log_msg "debug" "MSM_FLAG_YES=${MSM_FLAG_YES}"

	case "${sub_command}" in
	restore)
		default_restore
		;;
	decommission)
		default_decommission
		;;
	*)
		usage
		;;
	esac
}

main "${@}"

exit 0
