#!/bin/ash

logdir=/log
tmpmount=/loopfs

usage () {
   cat << EOF 
usage: $0 <devicename>

This script is used to dump logs to some portable storage device, to be 
retrieved later for analysis. Typically, a USB storage device formatted 
with a Linux or MSDOS filesystem is used. A device partition, as it 
appears to the I/O subsystem, must be specified for <devicename>.

(e.g. $0 sda1)
EOF
}

main () {
   if [ $# -ne 1 ]; then
      usage
      exit 1
   fi

   # Get/check.
   devname=$1
   devnum=`grep " $devname " /proc/partitions | sed 's/ \+/ /g' | cut -d' ' -f2,3` 
   if [ ! -n "$devnum" ]; then
      echo "$devname: No such device."
      usage
      exit 1
   fi

   # Get the priest too.
   dmesg -s 262144 > $logdir/dmesg
   echo "showlabels" | /sbin/nash --quiet > $logdir/labels

   if [ -r /proc/vmware/log ]; then
      cp /proc/vmware/log $logdir/vmkernel.log
   fi

   need=`du -s $logdir | cut -f1` 
   have=`grep " $devname " /proc/partitions | sed 's/ \+/ /g' | cut -d' ' -f4` 
   if [ $need -gt $have ]; then
      echo "Logs need $(($need + 1)) KB; $devname has only $have KB free."   
      exit 1
   fi

   # Make/mount.
   devnode=/dev/$devname
   if [ ! -b $devnode ]; then
      mknod $devnode b $devnum 
   fi

   mount $devnode $tmpmount 
   if [ $? -ne 0 ]; then
      echo "Unable to mount filesystem on $devname."
      echo "Make sure it's a formatted partition with a Linux or MSDOS filesystem."
      exit 1
   fi

   # Dump.
   cp -R $logdir /proc/scsi /proc/partitions $tmpmount 
   if [ $? -ne 0 ]; then
      echo "Failed to copy logs to $devname."
      exit 1
   fi

   umount $tmpmount
   echo "Logs have been copied to the directory '$logdir' on the device."
}

main $*
