#!/usr/bin/env bash
# One-shot TLS + nginx reverse-proxy setup for the AVC phone agent.
# RUN AS ROOT:  sudo bash deploy/setup-tls.sh
#
# Prerequisites (must be true BEFORE running):
#   - DNS: voip.activeblue.net -> your WAN IP        (done: 66.23.239.222)
#   - Router forwards external 80 AND 443 -> this box (10.10.1.221)
#   - nginx running with its default :80 site (used to answer the ACME challenge)
#
# What it does: installs certbot, gets a Let's Encrypt cert via the webroot challenge
# (served by the existing default :80 site), installs the vhost + ws-upgrade map, then
# tests and reloads nginx. Idempotent-ish; safe to re-run.
set -euo pipefail

DOMAIN="voip.activeblue.net"
EMAIL="mr.garcia09@gmail.com"
APP_DIR="/home/tocmo0nlord/avc-phone"
WEBROOT="/var/www/html"

if [ "$(id -u)" -ne 0 ]; then echo "Run as root (sudo)."; exit 1; fi

echo "==> 1/4 install certbot"
if ! command -v certbot >/dev/null 2>&1; then
  apt-get update && apt-get install -y certbot
fi

echo "==> 2/4 obtain certificate for $DOMAIN (webroot challenge)"
mkdir -p "$WEBROOT/.well-known/acme-challenge"
certbot certonly --webroot -w "$WEBROOT" -d "$DOMAIN" \
  --non-interactive --agree-tos -m "$EMAIL" --keep-until-expiring

echo "==> 3/4 install nginx vhost + ws-upgrade map"
cp "$APP_DIR/deploy/nginx-ws-upgrade.conf"            /etc/nginx/conf.d/ws-upgrade.conf
cp "$APP_DIR/deploy/nginx-voip.activeblue.net.conf"   /etc/nginx/sites-available/voip.activeblue.net
ln -sf /etc/nginx/sites-available/voip.activeblue.net /etc/nginx/sites-enabled/voip.activeblue.net

echo "==> 4/4 test + reload nginx"
nginx -t
systemctl reload nginx

echo
echo "Done. Verify:  curl https://$DOMAIN/health"
echo "Cert auto-renews via the certbot systemd timer; nginx reload on renew is handled by certbot's deploy hook."
