#!/usr/bin/env bash
# rebuild.sh — tear down containers ONLY (keeps pool/bridge/profile) and
# rebuild the cluster from scratch. Use --full to also wipe LXD itself first.
set -euo pipefail
cd "$(dirname "$0")/.."

FULL=false
[[ "${1:-}" == "--full" ]] && FULL=true

echo "==> Deleting existing containers (if present)"
for c in k8master k8worker1; do
  if lxc info "$c" &>/dev/null; then
    lxc delete "$c" --force
  fi
done

if $FULL; then
  echo "==> --full requested: purging LXD entirely first"
  bash scripts/uninstall.sh --yes
  bash scripts/00-init-lxd.sh
fi

echo "==> Recreating containers"
bash scripts/01-create-containers.sh

for node in k8master k8worker1; do
  echo "==> Installing common packages on ${node}"
  lxc file push scripts/02-node-common-setup.sh "${node}/root/setup.sh"
  lxc exec "${node}" -- bash /root/setup.sh
  lxc snapshot "${node}" packages-installed
done

echo "==> Bootstrapping control plane"
lxc file push scripts/03-init-master.sh k8master/root/init-master.sh
lxc exec k8master -- bash /root/init-master.sh
lxc snapshot k8master control-plane-ready

echo "==> Joining worker"
bash scripts/04-join-worker.sh

echo "==> Validating"
bash scripts/validate.sh

echo "==> Rebuild complete."
