#!/usr/bin/bash
#
# Start a netboot VM connected to macvtap device and fraction of mem/cpus
#
set -eu

## Imporant for all virsh libvirt calls:
export XDG_CONFIG_HOME="/var/tmp/vm/${UID}"

menu=(standard-edu "CLI Standard Debian GNU/Linux NFS"
      standard-edu-ram "CLI Standard Debian GNU/Linux RAM"
      kde-edu "KDE Plasma Desktop Debian GNU/Linux NFS"
      gnome-edu "Gnome Desktop Debian GNU/Linux NFS")
img=$(dialog --clear --backtitle "Virtual Machine Chooser" \
             --title "Choose the Virtual Machine to Start" \
             --menu "Start VM:" 12 70 6 "${menu[@]}" 2>&1 >/dev/tty)

## If the menu is canceled, $0 stops here because of set -e

# FIXME: Use first device found for now:
mac="$(ip link | grep -A1 -m1 "macvtap-" | \
          sed -nE "s%\s+link/ether ([[:xdigit:]:]{17}) .+%\1%p")"
tapdev="$(ip link | grep -A1 -m1 "macvtap-" | sed -nE "s%^[1-9]:\s(\S+)@.*%\1%p")"

livebox=$(host livebox | sed -E "s/.+ ([0-9.]+)$/\1/")

if [[ $# -eq 0 ]] ; then
    mem=$(sed -En "s/^MemAvailable:\s+([0-9]+)\s+kB/\1/p" /proc/meminfo)
    cpu=$(sed -En "0,/^cpu cores/s/^cpu cores\s+:\s+([0-9]+)/\1/p" /proc/cpuinfo)
    arg=("--memory=$((mem/2048))" "--vcpu=$((cpu/2))")
    echo Set options: "${arg[@]}"
else
    arg=("$@")
fi

kernel="http://${livebox}/d-i/n-live/${img%-ram}/live/vmlinuz"
initrd="http://${livebox}/d-i/n-live/${img%-ram}/live/initrd.img"
kargs=(boot=live components splash locales=de_DE.UTF-8 keyboard-layouts=de
       swap=true live-config.timezone=Europe/Berlin)

case "$img" in
    standard*)
        arg+=(--autoconsole=text)
        kargs+=(console=ttyS0)
        ;;&
    *-ram)
        kargs+=("root=live:nfs4:${livebox}:/images/${img%-ram}/live/filesystem.squashfs rd.live.ram=1")
        ;;
    *)
        kargs+=("root=live:nfs4:${livebox}:/images/${img%-ram}/live/filesystem.squashfs")
        ;;
esac

type="ethernet,mac=${mac},target.dev=${tapdev},xpath1.set=./target/@managed=no"
n=0
for vm in $(virsh --connect qemu:///session list --all --name) ; do
    if virsh domiflist "$vm" | grep -q "$mac" ; then
	type="user"
	virt-manager &
    fi
    if [[ "${img}$n" = "$vm" ]] ; then
        n=$((n+1))
    fi
done
kargs+=(hostname="${img}$n")

## FIXME: use passt, needs more settings for correct DNS/gateway
# type=user,xpath1.create=./backend,xpath2.set=./backend/@type=passt,xpath3.create=./ip,xpath4.set=./ip/@family=ipv4,xpath5.set=./ip/@address=172.16.1.1,xpath6.set=./ip/@prefix=24,xpath7.create=./portForward,xpath8.set=./portForward/@proto=tcp,xpath9.set=./portForward/range/@start=2001,xpath10.set=./portForward/range/@end=2500,xpath11.set=./portForward/range/@to=1

http_proxy='' \
          exec virt-install \
          --name "${img}$n" \
          --osinfo debiantesting \
          --nodisks --import --noreboot --transient \
          --controller type=scsi,model=virtio-scsi \
          --install kernel="$kernel",initrd="$initrd",kernel_args="${kargs[*]}" \
          --network "type=$type" "${arg[@]}"

# --filesystem "$HOME",share
# mount -t 9p share /mnt
