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

BASENAME="mx-bootloader-mode-tool"
ENV_FLAG="prod_mode"

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

_get_env() {
    local mode_info
    mode_info=$(fw_printenv -n ${ENV_FLAG})
    echo "${mode_info}"
}

_get_secure_boot() {
    local secure_boot
    secure_boot=$(mx-interface-mgmt deviceinfo | sed -n '/SECUREBOOT/s/[^=]*=//p')
    echo "${secure_boot}"
}

info() {
    local mode

    if [ "$(_get_env)" = "1" ]; then
        mode="production"
    elif [ "$(_get_env)" = "0" ]; then
        mode="developer"
    else
        mode="unknown"
    fi

    if [ "$MBM_OPTION_JSON" = "y" ]; then
        jq -n --arg mode "$mode" '{currentMode: $mode}'
    fi

    $LOGGER_ECHO "$BASENAME" "Current mode: $mode"
}

set_production() {
    if [ "$(_get_secure_boot)" = "Disabled" ]; then
        $LOGGER_ECHO "$BASENAME" "Not allowed to switch modes on Standard Model"
        exit 1
    fi
    _set_env 1
    $LOGGER_ECHO "$BASENAME" "Set mode successfully"
    info
}

set_developer() {
    if [ "$(_get_secure_boot)" = "Disabled" ]; then
        $LOGGER_ECHO "$BASENAME" "Not allowed to switch modes on Standard Model"
        exit 1
    fi
    _set_env 0
    $LOGGER_ECHO "$BASENAME" "Set mode successfully"
    info
}

parsing_options() {
    while [ -n "$1" ]; do
        case "$1" in
        -i | --info | info)
            action=info
            shift
            ;;
        -p | --production | production)
            action=production
            shift
            ;;
        -d | --developer | developer)
            action=developer
            shift
            ;;
        -h | --help | help)
            $HELPER_MENU "mode"
            exit "${?}"
            ;;
        -J | --json)
            export MBM_OPTION_JSON=y
            shift
            ;;
        *)
            $HELPER_MENU "wrong" "mode"
            exit "${?}"
            ;;
        esac
    done

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

    return 0
}

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

    case "$action" in
    info)
        info
        ;;
    production)
        set_production
        ;;
    developer)
        set_developer
        ;;
    *) ;;
    esac

    return 0
}

main "$@"
