#!/bin/bash

VERSION="1.6.1"

PRODUCTION_LIB_NAME="productionLib.sh"
CONFIG_PATH="/etc/mptool.config"
SCRIPT_DIR="${0%/*}"
SCRIPT_FILE="${0##*/}"

DEBUG=${MPTOOL_DEBUG:-"0"}
SIMULATE=${MPTOOL_SIMULATE:-"0"}
	
if test -e "${SCRIPT_DIR}/${PRODUCTION_LIB_NAME}"; then
	echo "WARNING: Using production library ${SCRIPT_DIR}/${PRODUCTION_LIB_NAME}"
	PRODUCTION_LIB_PATH="${SCRIPT_DIR}/${PRODUCTION_LIB_NAME}"
else
	PRODUCTION_LIB_PATH="/usr/lib/mptool/${PRODUCTION_LIB_NAME}"
fi


if test "$DEBUG" != "0";then
	echo "DEBUG print enabled"
fi

#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=""
UPDATE_PARTITION_NAME=""
DEFAULT_FLASH_COMMAND="flash-bl-fs"

##############################################################################
#	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             Excecute default flash command from config file"
	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-partition <NAME> Update named partition's filesystem"
	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
		;;
	"flash")
		COMMAND="${DEFAULT_FLASH_COMMAND}"
		echo "Executing default flash command: ${COMMAND}"
		;;
	"update-partition")
		if test -n "${COMMAND}"; then
			echo "ERROR: Only one command is allowed! Got two commands: <${COMMAND}> and <${1}>"
			exit 1
		fi
		COMMAND="${1}"
		UPDATE_PARTITION_NAME="${2}"
		shift
		;;
	"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}"
		SPECIFIC_UPDATE_IMG="${2}"
	    shift
	    ;;
	-m|-u|-c)
		# Was parsed when reading config files
		shift
		;;
	-*)
		echo "ERROR: Invalid option <${1}>"
		exit 1
		;;
	"validate-uid")
		COMMAND="${1}"
		shift
		;;
	*)
		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 "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}"
		echo "borootfs img : ${BOROOTFS_IMG}"
		echo "rescuefs img : ${RESCUEFS_IMG}"
	else
		local med
		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
##############################################################################
#
# Config file read priorities
# ===========================
#
# Stage 1) Reading basic config file
# ----------------------------------
#
# if config file is not given on command line the config file will be searched in this
# sequence. If one config file is found searching aborts:
#
# /etc/mptool_<MEDIUM>.cfg
# /etc/mptool.cfg
# 
# If config file is given on command line only and exacly this config file is parsed in stage 1)
#
# --> For stage 1) EXACTLY ONE config file is read!
# 
# Stage 2) Reading configs dependent for firmware
# -----------------------------------------------
#
# In stage 2 config files are searched in FW_DIR. If one config file is found, search aborts:
#
# $FW_DIR/mptool_<MEDIUM>.cfg
# $FW_DIR/mptool.cfg
#
# --> In this stage zero or one config file is read.
#
read_config_file ()
{
    local cmdline_CONFIG_PATH
    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
            ;;
        -h)
            return
        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 in
	# default diretory /etc !
	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 OTP"
	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
	
	#determine if old config (v<1.3) with no partition layout
	if test "$FS_PARTITION_LAYOUT" = "" ;then
		echo "No partition layout defined, using standard \"BOROOTFS USERFS\" layout"
		
		boroot_IMG=$BOROOTFS_IMG
		boroot_SIZE=$BOROOTFS_SIZE
		boroot_BOOT="y"
		userfs_IMG=$USERFS_IMG
		userfs_SIZE=$USERFS_SIZE
		FS_PARTITION_LAYOUT="boroot userfs"
	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

	value=${value,,} # convert to lowercase

	otp_val=$(read_otp_register ${index})
	if test -z "${otp_val}"; then
		printStatus "Reading OTP register ${index} failed" 1
		return 1
	fi

	if test "${value}" == "0x00000000" -a "${otp_val}" == "00000000"; then
		# We can't distinguish between an unprogrammed register with value 0x00000000 and a
		# programmed one. So simply try for the rare case a 0x00000000 programmed register shall
		# be re-programmed with the same value.
		# Keep in mind: After programming OTP the bits are locked! So programming 0x00000000 a
		# second time leads to an programming error in tf-a
		printStatus "Value ${value} might be already programmed! Programming again may fail!"
	elif test "0x${otp_val}" == "${value}"; then
		printStatus "This register is already programmed (0x${otp_val})! Skip programming!"
		return 0
	elif test "${otp_val}" != "00000000"; then
		printStatus "Programming register cancelled! A different value (0x${otp_val}) is alread programmed" 1
		return 1
	fi


	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 $*

	validate_configuration
	if test $? != 0; then
		echo "ERROR: ${validate_configuration_ERRMSG}"
		exit 1
	fi

	# set defaults for tfa and uboot
	TFA_IMG="${FW_DIR}/${TFA_IMG}"
	UBOOT_IMG="${FW_DIR}/${UBOOT_IMG}"

	# process commands
	ui_show_configuration

	case "${COMMAND}" in

		"flash-bl-fs")
			flash_bootloader ${TFA_IMG} ${UBOOT_IMG}
			STATUS=$?
			if test "$STATUS" != 0; then
				printStatus "Flashing bootloader failed!" 1
			else
				flash_nand_emmc
				STATUS=$? 
				if test "$STATUS" != 0; then
					printStatus "Flashing file system failed!" 1
				fi
			fi
		;;
		"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 
			STATUS=$?
		;;
		"update-partition")
			update_specific_partition $UPDATE_PARTITION_NAME
			STATUS=$?
		;;

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

		"read-lan-mac")
			ui_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")
			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=$?
			;;
		"validate-uid")
			shift
			validate_kontron_uid_param $*
			STATUS=$?
			;;
		*)
			echo "ERROR: Command <${COMMAND}> not implemented"
			exit 1
		;;
	esac

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


main $*
