#!/usr/bin/env bash
# Create Nextcloud VM on Proxmox — run ON PVE host as root (Spec 034 Fase 0)
#
# Alvo Roger 2026-06-21: VM124 (após VM123) — NÃO usar VM118 nem VM116 (RustDesk).
# Recursos: 2 vCPU · 4 GB RAM · 500 GB disco (se storage local-lvm tiver espaço).
set -euo pipefail

VMID="${VMID:-124}"
NAME="${NAME:-vm124-nextcloud-ligbox}"
CORES="${CORES:-2}"
MEMORY="${MEMORY:-4096}"
DISK_GB="${DISK_GB:-500}"
BRIDGE="${BRIDGE:-vmbr0}"
STORAGE="${PVE_STORAGE:-local-lvm}"
ISO_STORAGE="${ISO_STORAGE:-local}"
UBUNTU_ISO="${UBUNTU_ISO:-ubuntu-24.04-live-server-amd64.iso}"
IP="${IP:-10.10.10.124/24}"
GW="${GW:-10.10.10.1}"
SSH_WAN_PORT="${SSH_WAN_PORT:-2524}"

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

echo "==> Storage disponível (${STORAGE}):"
pvesm status 2>/dev/null | grep -E "Name|${STORAGE}" || true

AVAIL_GB=$(pvesm status 2>/dev/null | awk -v s="$STORAGE" '$1==s {print int($7)}')
if [[ -n "${AVAIL_GB:-}" && "${AVAIL_GB}" -lt "${DISK_GB}" ]]; then
  echo "AVISO: ${STORAGE} tem ~${AVAIL_GB} GB livres; pedido ${DISK_GB} GB." >&2
  echo "Ajuste DISK_GB ou PVE_STORAGE antes de continuar." >&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 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."
else
  echo "ISO $UBUNTU_ISO não encontrada — instalar Ubuntu 24.04 manualmente."
fi

cat <<EOF

VM $VMID criada ($NAME).
Recursos: ${CORES} vCPU, ${MEMORY} MB RAM, ${DISK_GB} GB disco

Após Ubuntu 24.04:
  IP estático: ${IP}
  Gateway: ${GW}
  DNS: 1.1.1.1

Deploy stack:
  scp -r deploy/vm116-nextcloud root@${IP%/*}:/opt/
  ssh root@${IP%/*} bash /opt/vm116-nextcloud/scripts/bootstrap.sh
  cd /opt/vm116-nextcloud && cp .env.example .env && nano .env
  bash /opt/vm116-nextcloud/scripts/install.sh

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

Traefik CT114: cloud.ligbox.com.br → http://${IP%/*}:8080

NOTA: VM116 = RustDesk (não tocar). Nextcloud = VM124 apenas.

EOF
