#!/bin/bash

# verify_node_cfg
#
# Pedro Nuno Machado
# Siemens SA
# 20051011
#
# To be used in IF additional steps
#

# Name: verify_cksum
# Description: Verify the md5 sum in the node.cfg file.
# Input: $1 = path to node.cfg file
# Return code: 0 = ok
#              1 = fail (bad checksum)
#              2 = no checksum in file
#              3 = missing function argument
#              4 = file is missing or zero size
# Example:
#   verify_cksum /export/home/sis/jumpsrx/node0/node.cfg
#   echo "Return code: $?"
#
verify_cksum()
{
    _path=$1
    if [ "$_path" = "" ] 
    then
        return 3
    fi
    if [ ! -s $_path ]
    then
        return 4
    fi
    _cksum=`grep "checksum:" $_path | awk '{ print $3 }'`
    if [ -z "$_cksum" ] || [ "$_cksum" = "" ]
    then
        return 2
    fi
    # Generate a copy of the node.cfg without checksum line.
    # The last two lines are added by the checksum generator.
    _num=`wc -l $_path | awk '{ print $1 }'`
    if [ $_num -gt 2 ]
    then
        _num=`expr $_num - 2`
    fi
    head -$_num $_path > garb
    MD5SUM=`md5sum garb | awk '{ print $1 }'`
    rm garb
    if [ "$MD5SUM" = "$_cksum" ]
    then
        return 0
    fi
    return 1
}

# Name: main
# Description: Test if node.cfg exists in floppy and contains
# a valid checksum
# Input: none (assumed node.cfg is in /mnt/floppy)
# Return code: -1 = umount/mount failure
#		0 = ok
#		1 = fail (bad checksum)
#		2 = no checksum in file
#		4 = file is missing or zero size
# umount floppy
umount /dev/fd0
if [ $? -ne 0 ]; then
  echo "[FAIL] Floppy device not mounted"
  exit -1
fi

# mount again
mount /dev/fd0 /mnt/floppy
if [ $? -ne 0 ]; then
  echo "[FAIL] Floppy device can't be mounted"
  exit -1
fi

# verify checksum
verify_cksum /mnt/floppy/node.cfg
_res=$?
echo "Return code: $_res"
if [ $_res -eq 0 ]; then
  echo "[INFO] Valid node.cfg checksum"
  exit 0
elif [ $_res -eq 1 ]; then
  echo "[FAIL] Invalid node.cfg checksum"
  exit 1
elif [ $_res -eq 2 ]; then
  echo "[FAIL] No checksum in node.cfg"
  exit 2
elif [ $_res -eq 3 ]; then
  echo "[FAIL] Internal error"
  exit 3
elif [ $_res -eq 4 ]; then
  echo "[FAIL] Node.cfg missing or zero size"
  exit 4
fi
