#!/usr/bin/env bash
# Criar VM123 no Proxmox — executar NO HOST PVE como root
# HW: 2 vCPU, 4 GB RAM, 25 GB disco | IP: 10.10.10.123
set -euo pipefail

VMID=123
NAME=vm123-finance
CORES=2
MEMORY=4096
DISK_GB=25
BRIDGE=vmbr0
STORAGE="${PVE_STORAGE:-local-lvm}"
ISO_STORAGE="${ISO_STORAGE:-local}"
UBUNTU_ISO="${UBUNTU_ISO:-ubuntu-24.04-live-server-amd64.iso}"
IP=10.10.10.123/24
GW=10.10.10.1

if ! command -v qm &>/dev/null; then
  echo "Execute este script no host Proxmox." >&2
  exit 1
fi

if qm status "$VMID" &>/dev/null; then
  echo "VM $VMID já existe."
  qm config "$VMID"
  exit 0
fi

qm create "$VMID" \
  --name "$NAME" \
  --cores "$CORES" \
  --memory "$MEMORY" \
  --net0 "virtio,bridge=${BRIDGE}" \
  --scsihw virtio-scsi-pci \
  --scsi0 "${STORAGE}:${DISK_GB}" \
  --ostype l26 \
  --agent enabled=1 \
  --boot order=scsi0

if [[ -f "/var/lib/vz/template/iso/${UBUNTU_ISO}" ]] || pvesm list "${ISO_STORAGE}" 2>/dev/null | grep -q "$UBUNTU_ISO"; then
  qm set "$VMID" --ide2 "${ISO_STORAGE}:iso/${UBUNTU_ISO},media=cdrom"
  qm set "$VMID" --boot order=ide2\;scsi0
  echo "ISO anexada. Instalar Ubuntu 24.04 manualmente ou via cloud-init."
else
  echo "ISO não encontrada. Anexar Ubuntu 24.04 e instalar."
fi

cat <<EOF

VM $VMID criada.
Após instalar Ubuntu 24.04:
  IP estático: ${IP}
  Gateway: ${GW}
  DNS: 1.1.1.1

Copiar stack:
  scp -r deploy/vm123-finance-stack root@${IP%/*}:/opt/

Na VM123:
  bash /opt/vm123-finance-stack/bootstrap-vm123.sh
  cd /opt/vm123-finance-stack && cp .env.example .env && nano .env
  docker compose up -d
  bash install-openpanel.sh
  bash setup-foss-openpanel-module.sh

SSH WAN: porta 2523 (configurar DNAT pfSense → ${IP%/*}:22)

EOF
