#!/bin/sh

## Using SSH:
## *  Log in to hypervisor, retrieve list of running VMs
## *  Log in to hypervisor, retrieve list of ZFS volumes
## *  List any VM matching spec ^vpp[\d]+-[\d+]$
## *  List any ZFS datasets matching matching spec ^ssd-vol0/vpp[\d]+-[\d+]$
## *  If any of these exist, bail and require the user to run ./destroy first
##
##
## *  Log in to the hypervisor, and:
##     *  Clone the base image to all VM names (ssd-vol0/vpp0-[0-3])
##     *  Mount these in a staging directory
##     *  Rsync over our build/$(overlay)/$(hypervisor)/*
##     *  Unmount the staging directories
##     *  Start the VMs

BASE=${BASE:=vol0/hvn0.chbtl0.ipng.ch/ssd-vol0/vpp-proto-bookworm-disk0@20240114-release}
BUILD=${BUILD:=frr}
LAB=${LAB:=0}

[ -r .lock${LAB} ] && {
  echo "Lock file for LAB${LAB}, bailing"
  exit
}

## Do not touch below this line
LABDIR=/var/lab
STAGING=$LABDIR/staging
HVN="hvn${LAB}.lab.ipng.ch"

VMS=$(ls -1 build/${BUILD}/${HVN}/)

for VM in $VMS; do
  echo "[$VM] Cloning base"
  ssh root@$HVN "mkdir -p $STAGING/$VM; zfs clone $BASE vol0/$VM"
  echo "[$VM] Mounting in staging"
  ssh root@$HVN "mount /dev/zvol/vol0/$VM-part1 $STAGING/$VM"
  echo "[$VM] Rsyncing build"
  rsync -aIcg build/$BUILD/$HVN/$VM/ root@${HVN}:$STAGING/$VM/
  echo "[$VM] Running lab-build snippets"
  ssh root@$HVN "cd $STAGING/$VM; for s in root/lab-build/*; do chroot $STAGING/$VM /bin/bash /\$s; done"
  echo "[$VM] Unmounting and snapshotting pristine state"
  ssh root@$HVN "umount $STAGING/$VM; zfs snapshot vol0/${VM}@pristine"
  echo "[$VM] Copying libvirt config"
  scp -q build/${BUILD}/${HVN}/${VM}/root/libvirt.xml root@$HVN:${LABDIR}/${VM}.xml
  echo "[$VM] Defining libvirt config"
  ssh root@$HVN "virsh define ${LABDIR}/${VM}.xml"
done