#!/bin/bash
# Script to create an Ubuntu 22.04 cloud-init template in Proxmox

set -e

# --- CONFIG ---
VMID=9000
VM_NAME="ubuntu-22.04-cloudinit"
MEMORY=2048
CORES=2
STORAGE="local-lvm"      # Change if using different storage
BRIDGE="vmbr0"
IMG_URL="https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.img"
IMG_FILE="/tmp/jammy-server-cloudimg-amd64.img"

echo "==> Downloading Ubuntu 22.04 cloud image..."
wget -O "$IMG_FILE" "$IMG_URL"

echo "==> Creating VM $VMID ($VM_NAME)..."
qm create $VMID --name $VM_NAME --memory $MEMORY --cores $CORES --net0 virtio,bridge=$BRIDGE

echo "==> Importing disk to $STORAGE..."
qm importdisk $VMID "$IMG_FILE" $STORAGE

echo "==> Attaching disk..."
qm set $VMID --scsihw virtio-scsi-pci --scsi0 ${STORAGE}:vm-${VMID}-disk-0

echo "==> Adding cloud-init drive..."
qm set $VMID --ide2 ${STORAGE}:cloudinit

echo "==> Setting boot options..."
qm set $VMID --boot c --bootdisk scsi0

echo "==> Enabling serial console..."
qm set $VMID --serial0 socket --vga serial0

echo "==> Converting VM $VMID to template..."
qm template $VMID

echo "==> Cleaning up..."
rm -f "$IMG_FILE"

echo "✅ Template $VM_NAME (VMID $VMID) created successfully!"
