#!/bin/sh
# Deploy Homepage LXC (CT 120) on pve 192.168.1.216
set -e
PW="${PROXMOX_PASSWORD:-WaQTUw2t}"
PVE=192.168.1.216
VMID=120
APP="${HOMEPAGE_DIR:-/volume1/docker/homelab-configs/apps/homepage}"
STORAGE="${PVE_STORAGE:-Storage}"

ssh_pve() {
  docker run --rm -v "$APP:/src:ro" alpine sh -c "
    apk add --no-cache openssh-client sshpass rsync >/dev/null 2>&1
    sshpass -p '$PW' ssh -o StrictHostKeyChecking=no root@$PVE \"$1\"
  "
}

echo "=== Proxmox: LXC $VMID homepage ==="
if ssh_pve "pct status $VMID" 2>/dev/null | grep -q running; then
  echo "CT $VMID bestaat al en draait"
else
  if ssh_pve "pct status $VMID" 2>/dev/null | grep -q stopped; then
    echo "Start bestaande CT $VMID"
    ssh_pve "pct start $VMID"
  else
    echo "Maak CT $VMID aan..."
    ssh_pve "pct create $VMID local:vztmpl/debian-13-standard_13.1-2_amd64.tar.zst \
      --arch amd64 --cores 2 --memory 2048 --swap 512 \
      --hostname homepage --password '$PW' \
      --rootfs ${STORAGE}:8 \
      --net0 name=eth0,bridge=vmbr0,ip=dhcp,type=veth \
      --features nesting=1,keyctl=1 --unprivileged 1 --onboot 1"
    ssh_pve "pct start $VMID"
  fi
fi

echo "Wacht op netwerk..."
sleep 8

echo "=== Docker installeren ==="
ssh_pve "pct exec $VMID -- bash -c 'export DEBIAN_FRONTEND=noninteractive; \
  apt-get update -qq && apt-get install -y -qq docker.io docker-compose curl ca-certificates 2>/dev/null; \
  systemctl enable --now docker'"

echo "=== Config genereren ==="
python3 "$APP/generate-config.py" 2>/dev/null || true

echo "=== Config uploaden ==="
# tar config and push
tar -C "$APP" -czf /tmp/homepage-deploy.tgz docker-compose.yml config public websites-add.txt
docker run --rm -v /tmp:/tmp alpine sh -c "
  apk add --no-cache openssh-client sshpass >/dev/null 2>&1
  sshpass -p '$PW' scp -o StrictHostKeyChecking=no /tmp/homepage-deploy.tgz root@$PVE:/tmp/
"
ssh_pve "pct exec $VMID -- mkdir -p /opt/homepage && pct push $VMID /tmp/homepage-deploy.tgz /tmp/homepage-deploy.tgz"
ssh_pve "pct exec $VMID -- bash -c 'cd /opt/homepage && tar xzf /tmp/homepage-deploy.tgz && rm /tmp/homepage-deploy.tgz'"

echo "=== Homepage starten ==="
ssh_pve "pct exec $VMID -- bash -c 'cd /opt/homepage && docker compose pull && docker compose up -d'"

echo "=== IP ophalen ==="
IP=$(ssh_pve "pct exec $VMID -- hostname -I" | awk '{print $1}')
echo ""
echo "Klaar: http://${IP:-192.168.1.216}:3000"
echo "Of via pve-host als poort 3000 op CT staat: check Proxmox → CT $VMID"
