#!/bin/bash

STACK_NAME="brokenresolver"
echo "[+] Deploying DNS stack with project name: $STACK_NAME"

# === Step 1: Prepare Environment ===

# .env
if [ ! -f .env ]; then
  echo "[+] Creating dummy .env file..."
  cat <<EOF > .env
# === DUMMY CREDENTIALS ===
ICANN_USER=changeme@example.com
ICANN_PASS=changeme
FTP_USER=ftpuser
FTP_PASS=ftp123
FTP_SERVER=ftp.example.com
REMOTE_DIR=/public_html/zones
EOF
else
  echo "[i] .env exists, not touching it."
fi

# Warn if dummy credentials still in use
if grep -q "changeme" .env; then
  echo "[!] WARNING: .env contains dummy credentials. Update before production use!"
fi

# shared/token.txt
mkdir -p shared
if [ ! -f shared/token.txt ]; then
  touch shared/token.txt
  chmod 600 shared/token.txt
  echo "[+] Created shared/token.txt with secure perms."
fi

# unbound config
mkdir -p unbound
if [ ! -f unbound/unbound.conf ]; then
  echo "[+] Installing default Unbound config..."
  cp defaults/unbound.conf unbound/unbound.conf
fi

# nsd config
mkdir -p nsd/zones
if [ ! -f nsd/nsd.conf ]; then
  echo "[+] Installing default NSD config..."
  cp defaults/nsd.conf nsd/nsd.conf
fi

# cert store
mkdir -p certs

# CA init
if [ ! -f certs/rootCA.pem ]; then
  echo "[+] Bootstrapping Root CA via Docker..."
  docker compose -p $STACK_NAME run --rm local_ca ./init_ca.sh
fi

# === Step 2: Bring Down Old Stack ===
echo "[+] Shutting down existing $STACK_NAME stack..."
docker compose -p $STACK_NAME down -v --remove-orphans

# === Step 3: Rebuild & Deploy ===
echo "[+] Building Docker images..."
docker compose -p $STACK_NAME build

echo "[+] Launching containers..."
docker compose -p $STACK_NAME up -d

echo "[✓] Deployment complete. Your zones are sacred and your certs remain unmolested."
