#!/bin/bash

# Arian Nasr
# cloud-init provisioning for Debian 13 VM on Proxmox VE

template_vmid=106
newid=$(pvesh get /cluster/nextid)

# prompt for VM name
read -p "Enter the name for the new VM (default: vm-$newid): " vm_name
vm_name=${vm_name:-vm-$newid}
# prompt for customization
read -p "Enter the disk size in GB (default: 10): " disk
disk=${disk:-10}
# prompt for ssh key, if needed
read -p "Enter the SSH public key (optional): " ssh_key


# confirm the details before proceeding
echo "Creating VM with the following details:"
echo "Name: $vm_name"
echo "Disk Size: ${disk}GB"
if [ -n "$ssh_key" ]; then
    echo "SSH Key: Provided"
fi
read -p "Do you want to proceed? (y/N): " confirm
if [[ "$confirm" != "y" ]]; then
    echo "Aborting VM creation."
    exit 1
fi

pvesh create /nodes/$(hostname)/qemu/$template_vmid/clone \
    -newid $newid \
    -name "$vm_name" \
    -full true


# Resize the disk if needed
if [ $disk -gt 10 ]; then
    pvesh resize /nodes/$(hostname)/qemu/$newid/config \
        -scsi0 ${disk}G
fi

# Add SSH key if provided
if [ -n "$ssh_key" ]; then
    pvesh set /nodes/$(hostname)/qemu/$newid/config \
        -sshkeys "$ssh_key"
fi

# TODO:
# - Start VM
# - Wait for cloud-init to complete
# - Install qemu-guest-agent in VM
# - Reboot VM
# - Print IP address and status
