#!/bin/sh -e
#
# create VMs for the capsul service
# developed by Cyberia Heavy Industries
# POSIX or die

vmname="$1"
template_file="/tank/img/$2"
vcpus="$3"
memory="$4"
pubkeys="$5"
root_volume_size="25G"

if echo "$vmname" | grep -vqE '^capsul-[a-z0-9]{10}$'; then
  echo "vmname $vmname must match "'"^capsul-[a-z0-9]{10}$"'
  exit 1
fi

if [ ! -f "$template_file" ]; then 
  echo "template $template_file not found"
  exit 1
fi

if echo "$vcpus" | grep -vqE "^[0-9]+$"; then 
  echo "vcpus \"$vcpus\" must be an integer"
  exit 1
fi

if echo "$memory" | grep -vqE "^[0-9]+$"; then 
  echo "memory \"$memory\" must be an integer"
  exit 1
fi

echo "$pubkeys" | while IFS= read -r line; do
  if echo "$line" | grep -vqE "^(ssh|ecdsa)-[0-9A-Za-z+/_=@. -]+$"; then 
    echo "pubkey \"$line\" must match "'"^(ssh|ecdsa)-[0-9A-Za-z+/_=@. -]+$"'
    exit 1
  fi
done

disk="/tank/vm/$vmname.qcow2"
cdrom="/tank/vm/$vmname.iso"
xml="/tank/vm/$vmname.xml"

if [ -f /tank/vm/$vmname.qcow2 ]; then
    echo "Randomly generated name matched an existing VM! Odds are like one in a billion. Buy a lotto ticket."
    exit 1
fi

cp "$template_file" "$disk"
cp /tank/config/cyberia-cloudinit.yml /tmp/cloudinit.yml
echo "$pubkeys" | while IFS= read -r line; do
  echo "      - $line" >> /tmp/cloudinit.yml
done

cloud-localds "$cdrom" /tmp/cloudinit.yml

qemu-img resize "$disk" "$root_volume_size"
virt-install \
    --memory "$memory" \
    --vcpus "$vcpus" \
    --name "$vmname" \
    --disk "$disk",bus=virtio \
    --disk "$cdrom",device=cdrom \
    --os-type Linux \
    --os-variant generic \
    --virt-type kvm \
    --graphics vnc,listen=127.0.0.1 \
    --network network=public2,filterref=clean-traffic,model=virtio \
    --import \
    --print-xml > "$xml"

chmod 0600 "$xml" "$disk" "$cdrom"
virsh define "$xml"
virsh start "$vmname"

echo "success"