#!/bin/bash

if [ "${1}" == "?" -o "${1}" == "-h" ] ; then
	echo "usage: ${0} <number of ethernets> <pmon location> <pmon script location>"
	exit 1
fi

declare evmboardipaddr="172.18.43.43"
declare ethernetoui="00:02:d8"
declare -i numethers=${1}
declare manuftool=manufinfo
declare pmonlocation="${2}"
declare pmonscriptlocation="${3}"
declare tmpmanufout=manuf.out
declare delay=2

if [ -z "$(type -t ${manuftool})" ] ; then
    echo "Manufacturing tool, ${manuftool}, not found - exiting"
    exit 1
fi

while (( ${numethers} <= 0 )) ; do
    read -p "Enter number of ethernet interfaces: " answer
    let numethers=${answer}
    if (( ${numethers} <= 0 )) ; then
	echo "      number of ethernet interfaces must be greater than zero"
    fi
done

while [ ! -f ${pmonlocation:-""} ] ; do
    read -p "Enter pmon location: " answer
    pmonlocation=${answer}
done

while [ ! -f ${pmonscriptlocation:-""} ] ; do
    read -p "Enter pmon script location: " answer
    pmonscriptlocation=${answer}
done

echo "Number of ethernet interfaces: ${numethers}"
echo "      location of pmon binary: ${pmonlocation}"

while [ true ] ; do
    read -p "Enter last 6 hex digits of MAC 0 ethernet MAC address: " answer
    [ -z "${answer}" ] && continue
    [ "${answer:0:1}" == "q" ] && exit 0
    manufinfocmd="${manuftool} "    
    let ans=0x${answer}
    for (( index=0 ; ${index} < ${numethers} ; index=index+1 )) ; do
	let ans1="${ans}>>16"
	let ans1="${ans1}&0xff"
	let ans2="${ans}>>8"
	let ans2="${ans2}&0xff"
	let ans3="${ans}&0xff"
	macaddr=$(printf ":%02x" ${ans1} ${ans2} ${ans3})
	manufinfocmd="${manufinfocmd} ethaddr${index}=${ethernetoui}${macaddr}"
	let ans=ans+1
    done
    echo "COMMAND: ${manufinfocmd} > ${tmpmanufout}"
    ${manufinfocmd} > ${tmpmanufout}
    let savedstatus=${?}
    if [ ${savedstatus} != 0 ] ; then
	echo "ERROR: ${manuftool} either not found or failed"
	exit 1
    fi
    while [ true ] ; do
	echo "PINGing ${evmboardipaddr}"
	ping -n -c 1 -q -w 1 ${evmboardipaddr}
	let savedstatus=${?}
	if [ ${savedstatus} == 0 ] ; then
	    tftp ${evmboardipaddr} <<EOF
bin
rex 1
put ${tmpmanufout}
EOF
	    sleep ${delay}
	    pushd $(dirname ${pmonscriptlocation})
	    tftp ${evmboardipaddr} <<EOF
bin
rex 1
put $(basename ${pmonscriptlocation})
EOF
	    popd
	    sleep ${delay}
	    pushd $(dirname ${pmonlocation})
	    tftp ${evmboardipaddr} <<EOF
bin
rex 1
put $(basename ${pmonlocation})
EOF
	    popd
	    break
	fi
	sleep 5
    done
    rm -f ${tmpmanufout}
    read -p "Type q to quit, anything else to program more flash chips: " answer
    [ "${answer:0:1}" == "q" ] && exit 0
done

