#! /bin/bash

# fai-kvm, start kvm host for testing FAI software
#
# Author:    Thomas Lange, Uni Koeln, 2011-2017
# License:   GPL v2 or any later version

fix="-k en-us -smp 2 -cpu host -global isa-fdc.driveA= "  # if loading cirrusfb (via pcimodules and modprobe cirrusfb) causes errors in kvm
# without it centos initrd is not created properly and results in kernel panic

vga="-vga std"
user=1
size=10   # default size of the disk image
ram=2000
disks=1
cdimage=/files/scratch/fai-cd.iso # default name for CD image
diskdir=/tmp     # directory where the disk images will be created, a RAM disk is recommended
usernet=0
newdisk=0
daemonize=0
macprefix=52:54:00:11:23
# - - - - - - - - - - - - - - - - - - - - - - - - -
boot_disk() {

  # boot from disk
    [ -n "$1" ] && disk=$1
    case "$disk" in
	*.raw) f=",format=raw" ;;
    esac
    set -x
    kvm $gopt -boot order=c $net -drive file=$disk,if=virtio$f
}
# - - - - - - - - - - - - - - - - - - - - - - - - -
boot_pxe() {

  # PXE boot
  set -x
  kvm $gopt -boot order=nc $net $disk
}
# - - - - - - - - - - - - - - - - - - - - - - - - -
boot_cd() {

  [ -n "$1" ] && cdimage=$1
  # boot fai-cd
  set -x
  kvm $gopt -boot order=cd $net $disk -cdrom $cdimage
}
# - - - - - - - - - - - - - - - - - - - - - - - - -
die() {
  echo "$2" 1>&2
  exit $1
}

# - - - - - - - - - - - - - - - - - - - - - - - - -
usage() {

  cat <<EOF

 fai-kvm [options] pxe   # boot VM using PXE from NIC
 fai-kvm [options] disk [diskimage]  # boot VM from first disk
 fai-kvm [options] cd   [imagename]  # boot VM from an ISO image

 -b          run the VM daemonized in the background, no video output
 -n          create a new empty disk image, which is used as a local disk
 -N          recreate a new empty disk image, even if one already exists
 -s <size>   size of the local disk in GB (default is ${size}GB)
 -d <num>    number of local disks (default is 1)
 -D <path>   directory, where the disk image files are created (default: $diskdir)
 -m <mem>    RAM size  inMB (defaults is ${ram}MB)
 -u <num>    user number. This will become part of the MAC address of the interface
             of the VM and is the number of the tap device number. It is also used
             for the file name of the disk files. Each VM must have a unique number.
             If you have created 9 tap devies you can use the numbers 1 to 9.
 -V          do not use vga std with Bochs extensions, use the kvm default
 -U          Use kvm user networking instead of tap devices
 -t          Set title of the Qemu window

The MAC prefix is set inside the script to $macprefix:XX
EOF
  exit 0
}
# - - - - - - - - - - - - - - - - - - - - - - - - -

while getopts "bUhnNu:s:m:d:VD:t:" opt ; do
    case "$opt" in
        b) daemonize=1  ;;
        n) newdisk=1    ;;
        N) newdisk=2    ;;
        U) usernet=1 ;;
        u) user=$OPTARG ;;
        m) ram=$OPTARG ;;
        s) size=$OPTARG ;;
        d) disks=$OPTARG ;;
        D) diskdir=$OPTARG ;;
        t) title=$OPTARG ;;
        h) usage;;
        V) vga="";;
        ?) die 1 "Unknown option";;
    esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then
    echo Missing argument. pxe, cd or disk
    usage
    exit 1
fi

: ${title:=FAI-kvm-$user}
if ! [[ $user =~ ^[0-9]+$ ]] ; then
    die 2 "Error: Option -u needs a number"
fi
hex=$(printf %X $user)
diskfile=$diskdir/faitest-disk-$user

if [ $daemonize -eq 1 ]; then
    vga="-display none -daemonize -vnc :$user"
fi

# not all mac addresses work in kvm (or the bridge), be carefull when changing the first two bytes
# If you are generating your own MAC addresses you should use a value that contains 2,6,A or E as the second number as this defines a locally administered MAC address.
# x2:xx:xx:xx:xx:xx
# x6:xx:xx:xx:xx:xx
# xA:xx:xx:xx:xx:xx
# xE:xx:xx:xx:xx:xx

mac=$macprefix:$hex

if [ $usernet = 1 ]; then
    net="-net nic,name=eth0,model=virtio -net user,name=eth0"
else
    net="-net nic,macaddr=$mac,model=virtio -net tap,ifname=tap$user,script=no,downscript=no"
fi


disk=""
for i in `seq 1 $disks` ; do
  disk="$disk -drive file=$diskfile-$i.qcow2,if=virtio,index=$i"
  if [ $i -eq 1 ] ; then
    disk="$disk"
  fi
done
gopt="$fix $vga -m $ram -name $title"


# create new disk images
if [ X$newdisk != X0 ]; then
  for i in `seq 1 $disks` ; do
      if [ X$newdisk = X1 -a -f $diskfile-$i.qcow2 ]; then
	  echo "Will not overwrite disk image. Please use -N."
	  exit 3
      fi
      rm -f $diskfile-$i.qcow2
      qemu-img create -f qcow2 -o preallocation=metadata $diskfile-$i.qcow2 ${size}G
  done
fi

case "$1" in
    pxe) boot_pxe ;;
    cd) boot_cd $2 ;;
    disk) boot_disk $2 ;;
    *)
        echo "Missing argument." >&2
        usage
        ;;
esac
