#!/bin/bash
set -e

if [[ $# -lt 3 ]] ; then
    cat <<-EOF
USAGE (RAM in megabytes)

create_vm VMNAME RAM CPUS DISKSIZE
EOF
    exit 1
fi
VMNAME=$1
RAM=$2
CPUS=$3
DISKSIZE=${4:-10} # 10GB default

# Directory where image files will be stored
IMAGE_DIR=/var/lib/libvirt/images
IMAGE_FILE=${VMNAME}.qcow2
IMAGE_PATH=$IMAGE_DIR/$IMAGE_FILE
CIDATA_PATH=${IMAGE_DIR}/cidata-${VMNAME}.iso
BASE_FILE=${IMAGE_DIR}/base/ubuntu-20.04-server-cloudimg-amd64-disk-kvm.qcow2

# Create the VM image if it does not already exist
if [ ! -f "$IMAGE_PATH" ]; then
  echo "info: image file $IMAGE_PATH not found. creating new image"
  # Important: -F qcow2 is required to set the image format
  qemu-img create -b "$BASE_FILE" -f qcow2 -F qcow2 "$IMAGE_PATH" ${DISKSIZE}G
  chmod 600 "$IMAGE_PATH"
  if [ $? -ne 0 ]; then
    echo "error: failed to create image"
    exit 1
  fi
fi

# Dump the image info
qemu-img info "$IMAGE_PATH"

# Check if the cloud-init metadata file exists
# if not, generate it
if [ ! -r $CIDATA_PATH ]; then
  pushd $(dirname $CIDATA_PATH)
  mkdir -p $VMNAME
  cd $VMNAME

  cat > user-data <<-EOS
#cloud-config
ssh_authorized_keys:
  - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCw0I82gT8R4tpsqWGovLyjm2SR2F863MqNz224h3h/wl0xA5Eu0eRro+ELLv2hoebqQbcMsb89X5+7ObhDRar+b7tzDlXq4x+ECkAy6WbDSmBp3kNVd7muT4c9Zw7UxKsIvIm1ven1TkJ3UG80o6PyGiAUlBj4puIQwhp7OVknVutBBe8Rpp4f6BEuWluwpnPxc3KSaGhhr9p10xeX69cfspH40r8vHpI0zp19O5GpfYSOEH64UbwRpN2QypNB8ISmDHFsNGwdz0Ba4qrEOSGU9GveyOcsvEtt630/0fHqtbPBovOYu/FJISQZya2tofDig4EngBCJNfsPCbXFHtlp greg@karekinian.com
  - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDyUDR7ZE6HWmjvlfKrG8Ci+q5E4adbyboKvyYVkUXaTYt+DgisPPAqfGkd0yAHgVnmOS/3f5c3D6RrIXcxFmzwpV2BtmGZztBnEYvC5q8XPQhmu6AFl6ZDjh9XzUeO52py8tt5ZJ9W1R2ob/rlgX8txNHi6XwzuvPxZ7NR/iNup7cruBzkHABhwTvTfwaErufr6eNmNjh5VatNTei1ld6yWtmvbYJqJlpq6YyPu9vYNYPg0AB7I+OqOJhzHXhelY28GSP9KF3GDcHDtN1bV21g9+COcdKhMShQaw1WIkfQKdiuFictZIOCP0/uYSiFhyyoSvISiC3eT8zIimRbDRj basti@skddc.local

runcmd:
  # Enable serial console (for virsh)
  - systemctl enable serial-getty@ttyS0.service && systemctl start serial-getty@ttyS0.service
  - curl -s 'https://raw.githubusercontent.com/zerotier/ZeroTierOne/master/doc/contact%40zerotier.com.gpg' | gpg --import
  - curl -s -o /tmp/install_zerotier 'https://install.zerotier.com/'
  - cat /tmp/install_zerotier | gpg && bash /tmp/install_zerotier
  - zerotier-cli join 8541e5153eb4327c
EOS

  cat > meta-data <<-EOS
instance-id: $VMNAME
local-hostname: $VMNAME
EOS

  genisoimage -output "$CIDATA_PATH" -volid cidata -joliet -rock user-data meta-data
  chown libvirt-qemu:kvm "$CIDATA_PATH"
  chmod 600 "$CIDATA_PATH"
  popd
fi

# setting --os-variant to ubuntu20.04 and ubuntu18.04 breaks SSH and networking
virt-install \
  --name "$VMNAME" \
  --ram "$RAM" \
  --vcpus "$CPUS" \
  --cpu host \
  --arch x86_64 \
  --os-type linux \
  --os-variant ubuntu16.04 \
  --hvm \
  --virt-type kvm \
  --disk "$IMAGE_PATH" \
  --cdrom "$CIDATA_PATH" \
  --boot hd \
  --network=bridge=virbr0,model=virtio \
  --graphics none \
  --serial pty \
  --console pty \
  --autostart \
  --import
