#!/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.
#
# Name:
#	MOXA Bootloader Decommission Utility
#
# Description:
#	Set/Get MOXA Bootloader Decommission Mode
#
# Copyright (C) Moxa, Inc. All rights reserved.
# Copyright (C) 2022	Henry LC Chen	<HenryLC.Chen@moxa.com>

BASENAME="mx-bootloader-decommission-tool"
INTERFACE_NAME="mx-bootloader-mgmt decommission"
ENV_FLAG="decommission"

_logger() {
	echo "$1"
	logger -i -t $BASENAME "$1"
}

_question() {
	local yes="$1"
	local message="$2"
	local choice

	if [ "$yes" != "y" ]; then
		read -r -p "$message" choice
		if [ "${choice,,}" != "y" ]; then
			exit 1
		fi
	else
		echo "${message}${yes}"
	fi
}

usage() {
	echo "Reset bootloader configuration and clear all logs"
	echo
	echo "USAGE:"
	echo "    $INTERFACE_NAME [SUBCOMMAND]"
	echo
	echo "FLAGS:"
	echo "    -y, --yes                       Automatic yes to prompts"
	echo "    -h, --help                      Display the help menu"
	echo
	echo "SUBCOMMANDS:"
	echo "    info                      Get the bootloader decommissioning status"
	echo "    set                       Set decommission action, which will reset bootloader configuration and clear all logs upon next boot"
	echo "    unset                     Cancel decommissioning plan"
	echo
}

_set_env(){
	fw_setenv $ENV_FLAG "$1"
}

_get_env(){
	fw_printenv $ENV_FLAG
}

info() {
	_logger "Decommission info: $(_get_env)"
}

set_decommission(){
	_question "$assume_yes" "【Notice】This operation will delete all settings and records in the bootloader. Do you want to continue? (y/N)"
	_set_env 1
	_logger "Set decommission Done"
	info
}

remove_decommission(){
	_set_env
	_logger "Remove decommission configuration Done"
	info
}

parsing_options() {
	while [ -n "$1" ]; do
		case "$1" in
		-i | --info | info)
			action=info
			shift
			;;
		-s | --set | set)
			action=set_decommission
			shift
			;;
		-r | --remove | unset)
			action=remove_decommission
			shift
			;;
		-y | --yes)
			assume_yes=y
			shift
			;;
		-h | --help | help)
			usage
			exit 0
			;;
		*)
			usage
			exit 1
			;;
		esac
	done

	if [ -z "$action" ]; then
		return 1
	fi

	return 0
}

main() {
	if ! parsing_options "$@"; then
		usage
		exit 1
	fi

	case "$action" in
	info)
		info
		;;
	set_decommission)
		set_decommission
		;;
	remove_decommission)
		remove_decommission
		;;
	*)
		;;
	esac

	return 0
}

main "$@"
