#!/bin/bash
#
# check0.sh: Check the boot files on the USB key which have been used for 
# booting. 
# For this check it should be placed e. g. at /root/bin/boot0/
# and started via /etc/rc.local, with this appended two lines 
# (without #, before the exit line in rc.local):
# cd /root/bin/boot0
# nohup ./check0.sh &

# Dr. Rolf Freitag, 2009-12-07, Version 1.0


# for debugging
set -x 

# USB key device and partition: ususally sdb/sdb1 (for /dev/sdb sdb1) with one HDD, ...
KEYDEVICE="sdb"
KEYPARTITION="$KEYDEVICE"1

# list of the boot files on the key, with space as sequence operator
FILES="ldlinux.sys syslinux.cfg boot/initrd boot/vmlinu"

# logfile
LOGFILE="check0.log"

# tmpfile for mbr
TMPFILE_MBR="mbr.tmp"

# loop counter for counting files; start with 1 for MBR
typeset -i i=1

# return value counter
typeset -i j=0

# mount the USB key
mkdir -p /mnt/"$KEYPARTITION"
mount /dev/"$KEYPARTITION" /mnt/"$KEYPARTITION"

#make clean/empty
>"$LOGFILE"
rm -rf "$TMPFILE_MBR"

# check the files
for f in $FILES ; do 
  diff -q "$f" /mnt/"$KEYPARTITION"/"$f" >> "$LOGFILE"
  j=$(( $j + $? ))
  i=$(( $i + 1  ))
done

# check the MBR
dd if=/dev/"$KEYDEVICE" of="$TMPFILE_MBR" bs=512 count=1
diff mbr.original "$TMPFILE_MBR" >> "$LOGFILE"
j=$(( $j + $? ))

umount /mnt/"$KEYPARTITION" &

# mail the check result
cat "$LOGFILE" | mail -s "$j of $i boot files are corrupted" root@localhost

# beep if something is wrong
if [ $j -ne 0 ] ; then

  # beep via speaker (install package beep before)
  /usr/bin/beep -l 1234

  # noise via loudspeaker
  dd if=/dev/urandom of=/dev/dsp bs=1 count=123456
fi

