#! /bin/bash

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

fix="-k en-us -smp 2 -cpu host -global isa-fdc.fdtypeA=none "  # 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=
user=1
size=10G   # default size of the disk image
ram=2G
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
portbase=5900
usernet=0
newdisk=0
daemonize=0
efi=0
order=cd
usenvme=0
spice=0

# 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

macprefix=52:54:00:11:23
# - - - - - - - - - - - - - - - - - - - - - - - - -
boot_disk() {

  # boot from disk
    local ldisk
    local f

    [ -n "$1" ] && disk=$1
    shift
    case "$disk" in
	*.raw) f=",format=raw" ;;
    esac

    if [ $usenvme -eq 1 ]; then
        ldisk="-drive file=$disk,if=none$f,id=nvme1 -device nvme,serial=SN123450001,drive=nvme1"
    else
        ldisk="-drive file=$disk,if=virtio$f "
    fi
    set -x
    kvm $gopt -boot order=c $net $ldisk $*
}
# - - - - - - - - - - - - - - - - - - - - - - - - -
boot_pxe() {

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

  [ -n "$1" ] && cdimage=$1
  shift
  # boot fai-cd
  set -x
  kvm $gopt -boot order=$order $net $disk -cdrom $cdimage $*
}
# - - - - - - - - - - - - - - - - - - - - - - - - -
boot_usb() {

  [ -n "$1" ] && iso=$1
  shift
  # boot an USB stick
  set -x
  kvm $gopt -boot order=$order $net $disk -drive if=none,id=stick,format=raw,file=$iso -device nec-usb-xhci,id=xhci -device usb-storage,bus=xhci.0,drive=stick,bootindex=1 $*
}
# - - - - - - - - - - - - - - - - - - - - - - - - -
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 a   CD ISO image
 fai-kvm [options] usb  [imagename]  # boot VM from an USB ISO image

 fai-kvm [options] pxe|cd|disk [imagename] -- [more options for kvm]

 -b          run the VM daemonized in the background, no video output, activates VNC unless -S was added
 -S          activate the spice remote protocol on port 5900+<user number>, add -b for running in the background
 -E          Boot the VM with UEFI instead of legacy BIOS
 -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 (default is ${size}), a suffix like M,G,T can be used.
 -d <num>    number of local disks (default is 1)
 -D <path>   directory, where the disk image files are created (default: $diskdir)
 -M          Create NVMe drives instead of SATA disks. You may want to add -E.
 -m <mem>    RAM size (defaults is ${ram}), a suffix like M,G,T can be used.
 -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.
 -U          Use kvm user networking instead of tap devices
 -O          Swap boot order when booting an ISO. Default order is local disk, then ISO.
 -t          Set title of the Qemu window

You can add more options for kvm after --
The MAC prefix is set inside the script to $macprefix:XX
EOF
  exit 0
}
# - - - - - - - - - - - - - - - - - - - - - - - - -

while getopts "EbUhnNu:s:SMm:d:D:t:O" opt ; do
    case "$opt" in
        O) order=dc  ;;
        b) daemonize=1  ;;
        E) efi=1  ;;
        n) newdisk=1    ;;
        N) newdisk=2    ;;
        M) usenvme=1    ;;
        U) usernet=1 ;;
        u) user=$OPTARG ;;
        m) ram=$OPTARG
           if [ -z "${ram//[0-9]}" ]; then
               ram="${ram}G"
           fi
           ;;
        s) size=$OPTARG
           if [ -z "${size//[0-9]}" ]; then
               size="${size}G"
           fi
           ;;
        S) spice=1 ;;
        d) disks=$OPTARG ;;
        D) diskdir=$OPTARG ;;
        t) title=$OPTARG ;;
        h) usage;;
        ?) 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 %02X $user)
diskfile=$diskdir/faitest-disk-$user

port=$(($portbase + $user))
if [ $spice -eq 1 ]; then
    vga="-vga qxl -spice port=$port,disable-ticketing=on"
fi
if [ $daemonize -eq 1 ]; then
    if [ $spice -eq 1 ]; then
        vga+=" -daemonize -display none"
    else
        vga="-daemonize -display none -vnc :$user"
    fi
fi

mac=$macprefix:$hex

if [ $usernet = 1 ]; then
    net="-device virtio-net-pci,netdev=net0 -netdev user,id=net0"
else
    net="-device virtio-net-pci,netdev=net0,mac=$mac -netdev tap,ifname=tap$user,id=net0,script=no,downscript=no
"
fi


# 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}
  done
fi

disk=""
for i in $(seq 1 $disks) ; do
    if [ ! -f $diskfile-$i.qcow2 ]; then
        echo "WARN: $diskfile-$i.qcow2 not found. Ignoring."
        continue
    fi
    if [ $usenvme -eq 1 ]; then
        disk="$disk -drive file=$diskfile-$i.qcow2,if=none,id=nvme$i -device nvme,serial=SN12345000$i,drive=nvme$i"
    else
        disk="$disk -drive file=$diskfile-$i.qcow2,if=virtio,index=$i"
    fi
    if [ $i -eq 1 ] ; then
    disk="$disk"
  fi
done
gopt="$fix $vga -m $ram -name $title"
if [ $efi = 1 ]; then
    if [ ! -f /usr/share/ovmf/OVMF.fd ]; then
	die 99 "UEFI firmware not found. Please install package ovmf."
    fi
    if [ "$newdisk" -eq 2 ]; then # always overwrite
        cp -v /usr/share/OVMF/OVMF_VARS.fd $diskdir/faitest-uefi-$user-OVMF_VARS.fd
    fi
    if [ "$newdisk" -eq 1 ] && [ ! -f $diskdir/faitest-uefi-$user-OVMF_VARS.fd ]; then
        cp -v /usr/share/OVMF/OVMF_VARS.fd $diskdir/faitest-uefi-$user-OVMF_VARS.fd
    fi
    gopt="-drive if=pflash,format=raw,unit=0,readonly=on,file=/usr/share/OVMF/OVMF_CODE.fd \
          -drive if=pflash,format=raw,unit=1,file=$diskdir/faitest-uefi-$user-OVMF_VARS.fd $gopt"
fi


# Loop through parameters until '--' to pass the remainder to kvm.
# The preceding parameters are stored in $param1 & $param2
# param1 = cd|pxe|pxe ; param2 = diskimage | imagename
param1=""
param2=""
while [[ $# -gt 0 ]]; do
  if [ "$1" = "--" ]; then
	  shift
	  break
  fi
  param1="$param2"
  param2="$1"
  shift
done

# if we only have one parameter before '--'
if [ -z "$param1" ]; then
  param1="$param2"
  param2=""
fi

case "$param1" in
    pxe) boot_pxe $* ;;
    cd) boot_cd $param2 $* ;;
    usb) boot_usb $param2 $* ;;
    disk) boot_disk $param2 $* ;;
    *)
        echo "Wrong argument. Use one of pxe, cd, disk." >&2
        usage
        ;;
esac
