#!/usr/bin/env bash
# Put the Wave Bot on a secure https:// address.   Usage (as root):  bash deploy/setup-https.sh wavebot.yourdomain.com
set -euo pipefail
DOMAIN="${1:-}"
[ -n "$DOMAIN" ] || { echo "Usage: bash deploy/setup-https.sh wavebot.yourdomain.com"; exit 1; }
IP=$(curl -s4 --max-time 8 https://api.ipify.org || hostname -I | awk '{print $1}')
RESOLVED=$(getent ahostsv4 "$DOMAIN" 2>/dev/null | awk '{print $1; exit}' || true)
if [ "$RESOLVED" != "$IP" ]; then
  echo "$DOMAIN points to '${RESOLVED:-nothing}', but this server is $IP."
  echo "Add an A record for it in your DNS (cPanel Zone Editor), wait a few minutes, then run this again."
  exit 1
fi
echo "1/3 Installing Caddy (web server with automatic HTTPS)"
apt-get update -qq && apt-get install -y -qq caddy >/dev/null
echo "2/3 Configuring $DOMAIN"
cat > /etc/caddy/Caddyfile <<CADDY
$DOMAIN {
	encode gzip
	reverse_proxy 127.0.0.1:8090
	header {
		Strict-Transport-Security "max-age=31536000"
		X-Content-Type-Options nosniff
		-Server
	}
}
CADDY
caddy validate --config /etc/caddy/Caddyfile >/dev/null
echo "3/3 Opening the web ports and starting"
ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null
systemctl enable caddy >/dev/null 2>&1; systemctl reload caddy || systemctl restart caddy
sleep 8
if curl -s -o /dev/null -w '%{http_code}' "https://$DOMAIN/login" | grep -q 200; then
  echo; echo "Done. Admins can open:  https://$DOMAIN"
else
  echo "Caddy is starting; the certificate can take a minute. Then open https://$DOMAIN"
  echo "If it still fails:  journalctl -u caddy -n 30 --no-pager"
fi
