#!/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"
ENV_FLAG="decommission"

_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
}

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

_get_env() {
    decommission_status=$(fw_printenv $ENV_FLAG) # decommission=  or decommission=1
    decommission_status=${decommission_status//decommission=/}

    if [ -z "$decommission_status" ]; then
        decommission_status=false
    else
        decommission_status=true
    fi
}

info() {
    _get_env

    if [ "${MBM_OPTION_JSON}" = "y" ]; then
        jq -n --argjson decommission_status "${decommission_status}" '{decommissionStatus: $decommission_status}'
    fi

    $LOGGER_ECHO "$BASENAME" "Decommission status: ${decommission_status}"
}

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_ECHO "$BASENAME" "Set decommission Done"
    info
}

remove_decommission() {
    _set_env
    $LOGGER_ECHO "$BASENAME" "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)
            $HELPER_MENU "decommission"
            exit "${?}"
            ;;
        -J | --json)
            export MBM_OPTION_JSON=y
            shift
            ;;
        *)
            $HELPER_MENU "wrong" "decommission"
            exit "${?}"
            ;;
        esac
    done

    if [ -z "$action" ]; then
        $HELPER_MENU "wrong" "decommission"
        exit "${?}"
    fi

    return 0
}

main() {
    if ! parsing_options "$@"; then
        $HELPER_MENU "wrong" "decommission"
        exit "${?}"
    fi

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

    return 0
}

main "$@"
