#!/bin/bash
#
# iso-initrd.sh
# Copyright 2005 VMware, Inc.  All rights reserved.
#
# Initrd preparation script 
# - Copies binaries to the right places in the initrd fs. 
# - Creates the init scripts to be run at boot time.

PATH=/sbin:/usr/sbin:$PATH
export PATH

rdroot=""
kernel=""
showrc=""
isoRD=${ISORD:-}


createIsoScript() {
   mkdir -p $rdroot/init
   ISOSCRIPT=$rdroot/init/99.weasel
   cat > $ISOSCRIPT <<EOF
#!/bin/ash

echo mkdevices /dev | /bin/nash --force
mkdir -p /cdrom
mkdir -p /cram
mkdir -p /tmp
# XXX assumes hdc is the cdrom!
mount /dev/hdc /cdrom  
bin/insmod lib/loop.o
bin/insmod lib/cramfs.o
mount -o loop -o ro /cdrom/vmware/base/stage2.img /cram
export LD_LIBRARY_PATH=/usr/X11R6/lib
mount -o bind /tmp /cram/tmp
mount -o bind /dev /cram/dev
mount -o bind /proc /cram/proc
mount /cram/dev/pts /cram/dev/pts -t devpts
mount /cram/vmfs /cram/vmfs -t vmfs
chroot /cram /usr/bin/bash -c "/usr/bin/python /startx.py"
bin/shellrc 'last'
EOF
   chmod +x $ISOSCRIPT
   [ -n "$showrc" ] && echo "" && /bin/cat $ISOSCRIPT && echo ""
   echo "I'm done!"
   return 0
}

usage () {
    echo "Usage: `basename $0` [-r] <ramdisk root> <kernel>" 
    exit 1
}

main () {

   if [ $(id -u) != 0 ]; then
      echo "Must be run as root."
      exit 1
   fi

   while [ $# -gt 0 ]; do
      case $1 in
         -v)
               verbose=-v
               ;;
         -vv)
               verbose=-v
               showrc="yes"
               ;;

         --debug-esx)
               dbg_rd=yes
               ;;
         -r)
               refresh=1
               ;;
         *)
               if [ -z "$rdroot" ]; then
                  rdroot=$1
               elif [ -z "$kernel" ]; then
                  kernel=$1
               else
                  usage
               fi
               ;;
      esac

      shift
   done

   # Sanity.
   if [ -z "$rdroot" -o -z "$kernel" ]; then
      usage
   fi

   if [ ! -d "$rdroot" ]; then
      echo "Bad root dir." >&2
      exit 1
   fi
   
  if [ -n "$isoRD" ]; then
     createIsoScript
  fi
}
main $*
