#! /bin/sh

# This script makes a copy of an existing boot cd or iso on
#   disk so that we can add the Bacula code to it for remastering
#
# When we are done if there is no error, we should have the
#   cdrom image in cdimage
#

export LANG=C

# Print Usage message
usage () {
   cat <<END_OF_DATA
Usage: make_rescue_disk
  -h, --help             print this message
  --type=cdrom|iso       start with a cdrom or iso image
  --where=path           the path to the device (mounted) or the iso
END_OF_DATA
}

if [ ! `whoami` = "root" ] ; then
  echo ""
  echo "You need to be root to run this, otherwise"
  echo "I cannot mount the loopback. Continuing anyway ..."
  echo ""
fi


#
# Process command line options
#
for option in "$@" ; do
   case "$option" in
   -h | --help)
      usage
      exit 0
      ;;
   --type=cdrom)
      type=cdrom
      ;;
   --type=iso)
      type=iso
      ;;
   --where*)
      where=`echo "$option"|cut -c 9-`
      ;;
   *)
      echo "Unknown option specified: $option"
      usage
      exit 1
      ;;
   esac
done

if [ x$type == x ] ; then
   echo " "
   echo "You can make the rescue disk either from a mounted CDROM or"
   echo "from a .iso image. Please enter cdrom or iso:"
   read type   
   if [ $type == 'cdrom' ] ; then 
      echo "OK want mounted CDROM"
   elif [ $type == 'iso' ] ; then
      echo "OK want iso image"
   else
      echo "Type missing"
      exit 1
   fi
fi
if [ x$where == x ] ; then
   echo " "
   echo "Enter location of image e.g. /mnt/cdrom or /home/src/.../rescue.iso"
   read where
fi
if [ ! -e $where ]; then
   echo "Cannot find rescue image $where"
    exit 1
fi
if [ $type == iso ]; then
  rm -rf mnt
  mkdir mnt
  mount -o loop $where mnt
  if [ $? != 0 ] ; then
    echo "Mount failed."
    rm -rf mnt
    exit 1;
  fi
  rm -rf cdimage
  mkdir cdimage
  cp -a mnt/* cdimage/
  if [ $? != 0 ] ; then
    echo "Copy from iso to cdimage failed"
    unmount mnt
    rm -rf mnt cdimage
    exit 1;
  fi
  unmount mnt
  rm -rf mnt
fi
if [ $type == cdrom ] ; then
  rm -rf cdimage
  mkdir cdimage
  cp -a $where/* cdimage
  if [ $? != 0 ] ; then
    echo "Copy from cdrom to cdimage failed"
    rm -rf cdimage
    exit 1;
  fi
fi
#
