#! /bin/bash
#
# Compare a symbol size in a set of executables
#

usage()
{
  echo "$0: arguments *.exe"
  echo "  where arguments are:"
  echo "    -a architecture     target architecture (required)"
  echo "    -s symbol           symbol size to check (required)"
  echo "    -v                  verbose (default=no)"
  echo
}

check_fatal()
{
  if [ $1 -ne 0 ] ; then
    shift
    usage
    echo "ERROR: $*" >&2
    exit 1
  fi
}

toggle()
{
  if [ $1 = "no" ] ; then
    echo "yes"
    return
  fi
  echo "no"
}

#  Set up variables which control the scripts behavior
verbose=no
arch=NOT_SET
symbol=NOT_SET

while getopts a:s:v OPT
do
  case "$OPT" in
    a) arch="${OPTARG}" ;;
    s) symbol="${OPTARG}" ;;
    v) verbose=`toggle ${verbose}` ;;
    *) usage ; exit 1 ;;
  esac
done

shiftcount=`expr $OPTIND - 1`
shift $shiftcount

## Validate target architecture
case ${arch} in
  NOT_SET)
    usage
    echo "Architecture not specified"
    exit 1
    ;;
  *)
    type ${arch}-rtems5-nm >/dev/null 2>&1
    check_fatal $? "Architecture ${arch} is not valid"
    ;;
esac

if [ ${symbol} = NOT_SET ] ; then
  usage
  check_fatal 1 "Symbol not specified"
fi

echo "Size report for ${symbol}"
for exe in $*
do
  ${arch}-rtems5-nm -n ${exe} | grep ${symbol} >/dev/null 2>&1
  if [ $? -ne 0 ] ; then
    printf "%20s - Symbol not present\n" ${exe}
    continue
  fi
  start=`${arch}-rtems5-nm -n ${exe} | grep ${symbol} | cut -d' ' -f1`
  ln=`${arch}-rtems5-nm -n ${exe} | grep -n ${symbol} | cut -d':' -f1`
  ln=`expr ${ln} + 1`
  next=`${arch}-rtems5-nm -n ${exe} | sed -n ${ln},${ln}p | cut -d' ' -f1`

  nums=`echo ${next} ${start} | tr a-z A-Z`
  sz=`echo 16 i ${nums} - p | dc`
  printf "%20s - 0x%s - 0x%s (%d)\n" ${exe} ${start} ${next} ${sz}
done
exit 0
