#!/bin/bash

PATH_MAPT=/opt/fofb-opcua-server/app.mapt

function read_reg () {
	# ARGS: regname

	# Fix name for grep
	fname="^${1} "

	# Grep MAPT file for reg name
	l=$(grep -e ${fname} ${PATH_MAPT})

	if [[ -z "$l" ]]; then
		echo "Could not find register named $1" >&2
		exit 1
	fi


	# Retrieve fields
	raddr=$(awk '{print $3}' <<<$l )
	rsize=$(awk '{print $4}' <<<$l )

	# Read register
	data=$(devmem $raddr)

	echo $((data))
}

function get_appname () {

	appcode=$(read_reg APP.ID)

	if [[ $appcode -eq 0x507E17A0 ]]; then
		echo cellnode
		return
	fi
	

	if [[ $appcode -eq 0x507E1722 ]]; then
		echo centralnode
		return
	fi

	printf "Application ID not recognized: %X\n" $appcode  >&2
	echo \#NA
	return 1
}

function get_version () {

	vers=$(read_reg BSP.PRJ_VERSION)
	changes=$(($vers & 0xFF))
	patch=$(( $(($vers>>8)) & 0xFF))
	minor=$(( $(($vers>>16)) & 0xFF))
	major=$(( $(($vers>>24)) & 0xFF))

	shasum=$(printf "%x" $(read_reg BSP.PRJ_SHASUM))

	echo "${major}.${minor}.${patch}-${changes}-(${shasum})"
}

printf "%10s %s\n" $(get_appname) $(get_version)
printf "SynthTime: %s\n" "$(date -d"@$(read_reg BSP.PRJ_TIMESTAMP)")"
