#!/bin/sh

. /usr/local/bin/sig_catcher

status=0
primary=0
backup=0
executing=0
raw=0

#
# prints sp version info
#
# $1: the descriptive text
# $2: the version number
#
# depends on $raw and $booted primary being set before calling
#
printvers() {

    if [ $raw -eq 0 ]
	then
		echo -n "Booted "
	fi
	if [ -e /var/run/netboot_fw ]
	then
		echo -n network
	else
		if [ $booted_primary -gt 0 ]
		then
			echo -n primary
		else
			echo -n backup
		fi
	fi
	if [ $raw -eq 0 ]
	then
		echo -n " $1"
	fi
	echo " $2"

}

#
# print out the versin information
#
# $1: descriptive text
# $2: sp version
#
printversrunning() {

	if [ $raw -eq 0 ]
	then
		echo -n "$1 firmware version "
	fi
	echo $2
}

while [ $# -gt 0 ]
do
	case "$1" in
		-a)
			status=1
			primary=1
			backup=1;;
		-s)
			status=1;;
		-e)
			executing=1;;
		-p)
			primary=1;;
		-b)
			backup=1;;
		-r)
			raw=1;;
		-*)
			echo  usage: $0 [-a] [-e] [-p] [-b] [-s] [-r]
			echo
			echo 	-a	print all info
			echo	-e	print executing firmware version
			echo 	-p	print primary firmware version
			echo 	-b	print backup firmware version
			echo 	-s	print executing firmware version status
			echo 	-r	print raw information
			exit 0
	esac
	shift
done

PRIMARY=/mnt/jffs2_rootfs_primary
BACKUP=/mnt/jffs2_rootfs_backup
METADATA=/install/Metadata
platform=$(cat /var/run/platform)

primary_version=$(awk -F"=" '/RLM_package_version/ { split($2,a," ") ; print a[1] }' ${PRIMARY}/${METADATA} 2> /dev/null)
if [ -z "$primary_version" ] ; then
	primary_version="N/A"
fi
backup_version=$(awk -F"=" '/RLM_package_version/ { split($2,a," ") ; print a[1] }' ${BACKUP}/${METADATA} 2> /dev/null)
if [ -z "$backup_version" ] ; then
	backup_version="N/A"
fi
cur_version=$(awk -F"=" '/RLM_package_version/ { split($2,a," ") ; print a[1] }' ${METADATA} 2> /dev/null)
if [ -z "$cur_version" ] ; then
	cur_version="N/A"
fi

if [ -e /var/run/backup_fw ]
then
	booted_primary=0
else
	booted_primary=1
fi

if [ $status -gt 0 ] ; then
   printvers "firmware version" "$cur_version"
fi

[ $executing -gt 0 ] && printversrunning "Booted" "$cur_version"
[ $primary -gt 0 ] && printversrunning "Primary" "$primary_version"
[ $backup -gt 0 ] && printversrunning "Backup" "$backup_version"

