# create new LVM, netboot, ubuntu image
# Argumetns = -s [size] -v [vg] -n [name] -c [cfg out]
# Defaults = -s 8G -v xenny -n ubuntu -c [name].cfg
#!/bin/bash

usage()
{
cat << EOF
usage: $0 options

Create a new Ubuntu 12.04 LVM VM from netboot

OPTIONS:
   -h      Show this message
   -s      [disc size] (default 8G)
   -m      [memory] (default 512)
   -v      [LVM VG name]
   -n      [VM name]
   -c      [cfg out filename]
   -f      Finalize config file for normal use
EOF
}

finalize()
{
  # Finalize $CFG for normal use
  sed -i '/kernel/s/^/# /' $CFG
  sed -i '/ramdisk/s/^/# /' $CFG
  sed -i '/extra/s/^/# /' $CFG
  echo -e "bootloader = \"pygrub\"" >> $CFG
}

defaults()
{
  # Defaults if not flag assigned
  if [[ -z $SIZE ]]; then SIZE="8G"; fi
  if [[ -z $VG ]]; then VG="xenny"; fi 
  if [[ -z $NAME ]]; then NAME="ubuntu"; fi
  if [[ -z $CFG ]]; then CFG=`pwd`"/"$NAME".cfg"; fi
  if [[ -z $RAM ]]; then RAM="512"; fi
  MIRROR="http://mirror.anl.gov/pub/ubuntu/"
  LONGNAME="ubuntu-netboot-precise"
  IMGDIR="/var/lib/xen/images/$LONGNAME"
}

if [[ $EUID -ne 0 ]]; then
  echo "You must be a root user" 2>&1
  exit 1
else
  SIZE=
  VG=
  NAME=
  CFG=
  RAM=
  while getopts “hfs:m:v:n:c:” OPTION
  do
    case $OPTION in
      h)
        usage
        exit 1
        ;;
      s)
        SIZE=$OPTARG
        ;;
      m)
        RAM=$OPTARG
        ;;
      v)
        VG=$OPTARG
        ;;
      n)
        NAME=$OPTARG
        ;;
      c)
        CFG=$OPTARG
        ;;
      f)
        defaults
        finalize
        exit
        ;;
      ?)
        usage
        exit
        ;;
      esac
  done

  # Assign default values
  defaults
 
  # Create the LVM
  echo -e "\n> Creating LVM Container"
  lvcreate -L $SIZE -n $NAME /dev/$VG
  lvscan | grep $NAME

  # Grab the netboot initrd and vmlinuz
  echo -e "\n> Grabbing netboot/initrd"
  mkdir -p $IMGDIR
  cd $IMGDIR
  wget -nc $MIRROR/ubuntu/dists/precise/main/installer-amd64/current/images/netboot/xen/initrd.gz
  wget -nc $MIRROR/ubuntu/dists/precise/main/installer-amd64/current/images/netboot/xen/vmlinuz

  # Create .cfg file
  rm $CFG # fix?
  echo -e "\n> Creating" $CFG "file"
  echo -e "name = \""$NAME"\"" >> $CFG
  echo -e "memory = $RAM" >> $CFG
  echo -e "disk = ['phy:/dev/"$VG"/"$NAME",xvda,w']" >> $CFG
  echo -e "vif = [' ']" >> $CFG
  echo -e "kernel = \"$IMGDIR/vmlinuz\"" >> $CFG
  echo -e "ramdisk = \"$IMGDIR/initrd.gz\"" >> $CFG
  echo -e "extra = \"debian-installer/exit/always_halt=true -- console=hvc0\"" >> $CFG

  # Launch the vm
  read -n1 -p "Continue? (y/n) "
  echo  [[ $REPLY = [yY] ]] && echo Creating $NAME || { echo "Exiting..."; exit 1; }
  xm create -c $CFG
  
fi
