#!/bin/sh

VERSION="1.2.4"

CONFIG_PATH="/etc/mptool.config"
PRODUCTION_LIB_PATH="/usr/lib/mptool/productionLib-classic.sh"

#source base scripts
if [ -e $PRODUCTION_LIB_PATH ]; then
	. $PRODUCTION_LIB_PATH
else
	echo "ERROR: productionLib missing"
	exit 1
fi

STATUS=0

# Global options to control behaviour
COMMAND=""
OPT_CMDLINE_FILE=""
OPT_LAN_MACADDRESS=""
OPT_SOM_NUMBER=""
OPT_BOARD_NUMBER=""
OPT_VERBOSE=""
OPT_NOASK=""
OPT_OTP_REG_INDEX=""
OPT_OTP_REG_VALUE=""

##############################################################################
#	user interface shows help text
#	input: -
#	return: -
##############################################################################
ui_show_help ()
{
	echo "Usage:"
	echo "  mptool <COMMAND> [FLAGS]"
	echo 
	echo "Flash commands do (re)partition, erase and fill the device,"
	echo "upddate commands only erase and fill the device. The partitions"
	echo "must already exist!"
	echo ""
	echo "Commands for flashing:"
	echo "  flash-tfa         Flash tf-a (first stage) bootloader"
	echo "  flash-u-boot      Flash u-boot (second stage) bootloader"
	echo "  flash-full-bl     Flash all bootloaders (tf-a and u-boot)"
	echo "  flash-full-fs     Flash all filesystem partitions"
	echo "  flash-bl-fs       Flash all bootloaders and all filesystem partitions"
	echo ""
	echo "Commands for updating"
	echo "  update-borootfs     Update borootfs filesystem partition"
	echo "  update-userfs     Update userfs filesystem partition"
	echo "  update-rescuefs     Update rescuefs filesystem partition"
	echo "  update-full-fs    Update all filesystem partitions"   
	echo
	echo "Special OTP write and read commands"
	echo "  WARNING: Be careful, writing to OTP can only be done once!"
	echo "    A second write may fail or interfere with the previous value!"
	echo ""
	echo "  read-lan-mac      Read MAC address for first ethernet interface"
	echo "  set-lan-mac <MAC> Program MAC address for first ethernet interface"
	echo "                    MAC address has to be formatted as aa:bb:cc:dd:ee:ff"
	echo "  read-som-number   Read SOM number "
	echo "  set-som-number <n#ID> Program SOM number into OTP"
	echo "                    SOM number has be in format n##id"
	echo "  read-board-number Read SOM number "
	echo "  set-board-number <n#ID> Program BOARD number into OTP"
	echo "                    BOARD number has be in format n#id"
	echo "  read-boot-prios   Get bootup configuration"
	echo "  set-boot-prios    Set bootup configuration to SD, then NOR boot"
	echo "  read-otp-word <REG>"
	echo "                    Reads OTP word at location <REG>"
	echo "  set-otp-word <REG> <VALUE>"
	echo "                    Writes OTP word at location <REG>. REG has to be a decimal"
	echo "                    string, VALUE must be a 4 byte word (e.g. 0x123456778)"
	echo "  set-otp-defaults"
	echo "                    Writes all OTP words defined in the config file" 
	echo
	echo "Flags and options"
	echo "  Flags or options on commandline have higher priority"
	echo "  -m <MEDIUM>          Flash to medium (e.g. NAND or EMMC)"
	echo "  -c <FILENAME>        Use alternate config file (default ist /etc/mptool.config)"
	echo "  -u <DIRECTORY>       Set base directory for update files"
	echo "  -f <FILENAME>        Use FILENAME instead of filename in config file"
	echo "                       (Only valid for single file flash- or update commands)"
	echo "  -v                   Show version"
	echo "  --noask              Do not ask questions"
	echo "  --verbose            More verbose messages"
	echo ""
	echo "mptool version ${VERSION}"
}

##############################################################################
#	user interface function to output version information
#	input: -
#	return: -
##############################################################################
ui_show_version ()
{
	echo "Version: $VERSION"
	if [ ! -z $LIBVERSION ];then
		echo "Library version: $LIBVERSION"
	fi
}


##############################################################################
#	parse command line and set environment variable from arguments
#	Exits program if command line parsing fails
#	input: command line arguments
#	return: -
##############################################################################
parse_cmdline()
{
    while test "$1" != ""; do

	#echo "Processing parameter <${1}> / $*" 
	
	case ${1} in
	-h | --help)
		ui_show_help
		exit 0
		;;
	-v)
		ui_show_version
		exit 0
		;;

	"set-lan-mac")
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
		OPT_LAN_MACADDRESS="${2}"
		shift
		;;	
		
	"set-som-number")
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
		OPT_SOM_NUMBER="${2}"
		shift
		;;
	
	"set-board-number")
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
		OPT_BOARD_NUMBER="${2}"
		shift
		;;
		
	"set-otp-word")
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
		OPT_OTP_REG_INDEX="${2}"
		if test -z "${OPT_OTP_REG_INDEX}"; then
			echo "ERROR: Command requires register index"
			exit 1
		fi
		OPT_OTP_REG_VALUE="${3}"
		if test -z "${OPT_OTP_REG_VALUE}"; then
			echo "ERROR: Command requires register value"
			exit 1
		fi
		shift
		shift
		;;	

	"read-otp-word")
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
		OPT_OTP_REG_INDEX="${2}"
		if test -z "${OPT_OTP_REG_INDEX}"; then
			echo "ERROR: Command requires register index"
			exit 1
		fi
		shift
		;;	

	--verbose)
		OPT_VERBOSE=1
		;;
	--noask)
		OPT_NOASK=1
		;;
	-f)
		OPT_CMDLINE_FILE="${2}"
		TFA_IMG="${2}"
		UBOOT_IMG="${2}"
		BOOTFS_IMG="${2}"
		ROOTFS_IMG="${2}"
		USERFS_IMG="${2}"
	    shift
	    ;;
	-m|-u|-c)
		# Was parsed when reading config files
		shift
		;;
	-*)
		echo "ERROR: Invalid option <${1}>"
		exit 1
		;;
	*)
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
	esac
	shift
    done
    
    if test -z "${COMMAND}"; then
		ui_show_help
		echo "ERROR: No command given"
		exit 1
	fi
}

get_medium()
{
	local command=$1
	
	case ${command} in
	flash-tfa|flash-u-boot|flash-full-bl)
		echo "NOR"
		;;
	flash-bl-fs)
		echo >&2 TRAPPING
		echo "NOR/${MEDIUM}"
		;;
	flash-*|update-*)
		echo "${MEDIUM}"
		;;
	*)
		echo ""
		;;
	esac
}

##############################################################################
#	Show current configuration
#	input: -
#	return: -
##############################################################################
ui_show_configuration ()
{
	if test -n "${OPT_VERBOSE}"; then
		echo "Command      : ${COMMAND}"
		echo "Target medium: ${MEDIUM}"	
		echo "Config file  : ${CONFIG_PATH}"
		echo "base fw dir  : ${FW_DIR}"
		echo "tf-a image   : ${TFA_IMG}"
		echo "uboot image  : ${UBOOT_IMG}"
		echo "bootfs image : ${BOOTFS_IMG}"
		echo "userfs image : ${USERFS_IMG}"
		echo "rootfs image : ${ROOTFS_IMG}"
	else
		local med=$(get_medium ${COMMAND})
		echo "Command: ${COMMAND}"
		if test -n "${med}"; then
			echo "Target medium: ${med}"	
		fi
		if test -n "${OPT_CMDLINE_FILE}"; then
			echo "Update file: ${OPT_CMDLINE_FILE}"
		fi
	fi
}

##############################################################################
#	reads config file
#	
#	If config file is set by command line use this, else use config file in /etc
##############################################################################
read_config_file ()
{
    local cmdline_FW_DIR
    local cmdline_MEDIUM
    local found
    local config_base_file
    local config_base_file_ext
    local config_file_list
    
    while test "$1" != ""; do
        case ${1} in
        --verbose)
            OPT_VERBOSE=1
            ;;
        -c)
            cmdline_CONFIG_PATH=${2}
            CONFIG_PATH=${cmdline_CONFIG_PATH}
            config_file_list=${CONFIG_PATH}
            shift
            ;;
        -m)
            cmdline_MEDIUM=${2}
            MEDIUM=${cmdline_MEDIUM}
            shift
            ;;
        -u)
            cmdline_FW_DIR=${2}
            shift
            ;;
        esac
        shift
    done

	# source config
	# First search for config file mptool_${MEDIUM}.config, if not found mptool.config
	# If config file is given on command line do not search for ${MEDIUM} files!
	if test -z "${config_file_list}"; then
		config_base_file=$(echo ${CONFIG_PATH} | sed 's/\.[^.]*$//')
		config_base_file_ext=$(echo ${CONFIG_PATH} | sed 's/.*\././ ;t ;g')
		config_file_list="${config_base_file}_${MEDIUM}${config_base_file_ext} ${CONFIG_PATH}"
	fi
	for cfgfile in ${config_file_list}; do
		if test -n "${OPT_VERBOSE}"; then
			echo "Search for config file ${cfgfile}"
		fi
		if test -f "${cfgfile}" ;then
			echo "Reading config file ${cfgfile}"
			. $(realpath ${cfgfile})
			found="yes"
			break
		fi
	done
	
	if test -z "${found}"; then
		echo "ERROR: config file <${CONFIG_PATH}> not found"
		exit 1
	fi

	# Command line parameters have precedence over configuration files
	if test -n "${cmdline_MEDIUM}"; then
		MEDIUM=${cmdline_MEDIUM}
	fi
	if test -n "${cmdline_FW_DIR}"; then
		FW_DIR=${cmdline_FW_DIR}
	fi

	# Now search for mptool_${MEDIUM}.config and mptool.config file in ${FW_DIR}
	config_file_list="${FW_DIR}/mptool_${MEDIUM}.config ${FW_DIR}/mptool.config"
	for cfgfile in ${config_file_list}; do
		if test -n "${OPT_VERBOSE}"; then
			echo "Search for config file ${cfgfile}"
		fi
		if test -f "${cfgfile}" ;then
			echo "Reading config file ${cfgfile}"
			. $(realpath ${cfgfile})
			break
		fi
	done

	# Command line parameters have precedence over configuration files
	if test -n "${cmdline_MEDIUM}"; then
		MEDIUM=${cmdline_MEDIUM}
	fi
	if test -n "${cmdline_FW_DIR}"; then
		FW_DIR=${cmdline_FW_DIR}
	fi

}

##############################################################################
#	validates configuration (as possible)
#	input: -
#	return: 0 on succes 
#			1 on fail
##############################################################################
validate_configuration ()
{
	validate_configuration_ERRMSG=""
	local found=0
	
	VALID_MEDIUM_LIST="NAND EMMC"
	for device in ${VALID_MEDIUM_LIST}; do
		if test "${device}" = "${MEDIUM}"; then
			found=1
		fi
	done
	if test "$found" = "0"; then
		validate_configuration_ERRMSG="MEDIUM ${MEDIUM} is invalid. Supported values are: ${VALID_MEDIUM_LIST}"
		return 1
	fi
}

##############################################################################
#	User interface for ui_set_otp_word
#	References global variables
#	input: register index (dec), register value (hex e.g. 0x12345678)
#	return: 0 on succes 
#			1 on fail
##############################################################################
ui_set_otp_word()
{
	local index=$1
	local value=$2
	local confirmation

	if test -z ${OPT_NOASK}; then
		echo "Write ${value} to OTP${indes}. Continue ? (yes)"
		read confirmation
		if [ "$confirmation" != "yes" ];then
			echo "ERROR: No confirmation from user for wirting to OTP${index}"
			return 1
		fi
	fi

	write_otp_register "${index}" "${value}"
	if test 0 != $?; then 
		return 1
	fi
	echo "OTP${index}: $(read_otp_register ${index})"
	return 0
}

##############################################################################
#	User interface for ui_read_otp_word
#	References global variables
#	input: register index (decimal value)
#	return: 0 on succes 
#			1 on fail
##############################################################################
ui_read_otp_word()
{
	local index=$1
	local result

	result=$(read_otp_register ${index})
	if test 0 != $?; then
		return 1
	fi
	echo "OTP${index}: ${result}"

	return 0
}

##############################################################################
#	main program
#	References global variables
#	input: program arguments
#	return: -
##############################################################################
main ()
{
	read_config_file $*
	parse_cmdline $*

	# set defaults
	TFA_IMG="${FW_DIR}/${TFA_IMG}"
	UBOOT_IMG="${FW_DIR}/${UBOOT_IMG}"
	BOROOTFS_IMG="${FW_DIR}/${BOROOTFS_IMG}"
	USERFS_IMG="${FW_DIR}/${USERFS_IMG}"

	if [ "$RESCUEFS" == "y" ];then
		printStatus "include rescue fs" 
		RESCUEFS_IMG="${FW_DIR}/${RESCUEFS_IMG}"
	else
		RESCUEFS_IMG=""
		printStatus "Rescuefs=${RESCUEFS}" 
	fi
	validate_configuration
	if test $? != 0; then
		echo "ERROR: ${validate_configuration_ERRMSG}"
		exit 1
	fi

	# process commands
	ui_show_configuration

	case "${COMMAND}" in

		"flash-bl-fs")
			flash_bootloader ${TFA_IMG} ${UBOOT_IMG}
			STATUS=$?
			flash_nand_emmc ${BOROOTFS_IMG} ${USERFS_IMG} ${RESCUEFS_IMG}
			STATUS=$?
		;;
		"flash-full-bl")
			flash_bootloader ${TFA_IMG} ${UBOOT_IMG}
			STATUS=$?
		;;

		"flash-tfa")
			flash_tfa ${TFA_IMG}
			STATUS=$?
		;;

		"flash-u-boot")
			flash_uboot ${UBOOT_IMG}
			STATUS=$?
		;;
		
		"flash-full-fs")
			flash_nand_emmc ${BOROOTFS_IMG} ${USERFS_IMG} ${RESCUEFS_IMG}
			STATUS=$?
		;;
		"update-full-fs")
			update_nand_emmc ${BOROOTFS_IMG} ${USERFS_IMG} ${RESCUEFS_IMG}
			STATUS=$?
		;;
					
		"update-borootfs")
			flash_update_boroot ${BOROOTFS_IMG}
			STATUS=$?
		;;

		"update-rescuefs")
			flash_update_rescue ${RESCUEFS_IMG}
			STATUS=$?
		;;

		"update-userfs")
			flash_update_user ${USERFS_IMG}
			STATUS=$?
		;;

		"set-lan-mac")
			set_lan_mac ${OPT_LAN_MACADDRESS}
			STATUS=$?
			;;

		"read-lan-mac")
			read_lan_mac
			STATUS=$?
			;;	

		"read-som-number")
			read_som_number
			STATUS=$?
			;;
			
		"set-som-number")
			set_som_number ${OPT_SOM_NUMBER}
			STATUS=$?
			;;
			
		"read-board-number")
			read_board_number
			STATUS=$?
			;;
			
		"set-board-number")
			printStatus "${OPT_BOARD_NUMBER}" 1
			set_board_number ${OPT_BOARD_NUMBER}
			STATUS=$?
			;;
			
		"set-boot-prios")
			set_boot_prios
			STATUS=$?
			;;
			
		"read-boot-prios")
			read_boot_prios
			STATUS=$?
			;;

		"set-otp-word")
			ui_set_otp_word "${OPT_OTP_REG_INDEX}" "${OPT_OTP_REG_VALUE}"
			STATUS=$?
			;;

		"read-otp-word")
			ui_read_otp_word "${OPT_OTP_REG_INDEX}"
			STATUS=$?
			;;

		"set-otp-defaults")
			write_otps_from_config
			STATUS=$?
			;;
		*)
			echo "ERROR: Command <${COMMAND}> not implemented"
			exit 1
		;;
	esac

	if [ ${STATUS} -gt 0 ];then
		echo "ERROR: process failed with error " ${STATUS}
	else
		echo "OK: finished successfully"
	fi
}

main $*
