#!/usr/bin/bash

set -e

function cleanup {
  sync
  # Give some time to flush serial
  sleep 0.3
  echo "Shutting down VM"
  echo o > /proc/sysrq-trigger
  sleep 1000
}

trap cleanup EXIT

stty -onlcr

export PATH=/usr/bin:/usr/sbin

# Mount all "API" filesystems
mount -t proc proc /proc
mount -t sysfs sysfs /sys -o "seclabel"
mount -t tmpfs tmpfs /run -o "mode=0755,size=64m,seclabel"
mount -t tmpfs tmpfs /tmp -o "seclabel"
mount -t cgroup2 none /sys/fs/cgroup -o "seclabel"
mkdir /dev/shm
mount -t tmpfs none /dev/shm

# Make /etc transiently writable
mkdir -p /run/etc/upper /run/etc/work
mount -t overlay overlay -o "lowerdir=/etc,upperdir=/run/etc/upper,workdir=/run/etc/work" /etc

# Mount and initialize /var
mount -t ext4 /dev/vdb /mnt
if ! test -f /mnt/initialized ; then
   echo Initializing /var
   cp -ra /var/* /mnt/
   mount --move /mnt /var
  touch /var/initialized
else
   mount --move /mnt /var
fi

# Load container if given
if test -b /dev/vde; then
    podman load < /dev/vde
fi

# Mount virtio from host if given
modprobe virtiofs
if test -d /sys/bus/virtio/drivers/virtiofs/virtio?; then
    mount -t virtiofs host /mnt/
fi

# Run given script
bash /dev/vdc
echo "$?" > /dev/vdd
