#!/usr/bin/env bash
#
# Installs the Nginx site for the CMS and gets an HTTPS certificate.
# The domain's DNS must already point at this server.
#
#   sudo bash setup-nginx.sh cms-staging.secondlinenumber.com you@example.com
set -euo pipefail

DOMAIN="${1:-}"
EMAIL="${2:-}"
if [[ -z "$DOMAIN" || -z "$EMAIL" ]]; then
  echo "Usage: sudo bash $0 <domain> <email for Let's Encrypt>" >&2
  exit 1
fi
if [[ $EUID -ne 0 ]]; then
  echo "Run as root: sudo bash $0 $*" >&2
  exit 1
fi

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SITE=/etc/nginx/sites-available/secondline-cms

# Visitor IPs when the host is proxied through Cloudflare; included only if
# the line in the site config is uncommented.
{
  echo "# Cloudflare's address ranges, $(date -u +%F). Re-run setup-nginx.sh to refresh."
  for range in $(curl -fsS https://www.cloudflare.com/ips-v4) $(curl -fsS https://www.cloudflare.com/ips-v6); do
    echo "set_real_ip_from ${range};"
  done
  echo "real_ip_header CF-Connecting-IP;"
} > /etc/nginx/snippets/cloudflare-real-ip.conf

# Certbot edits the installed file; keep its HTTPS block when re-running.
if [[ -f "$SITE" ]] && grep -q "managed by Certbot" "$SITE"; then
  echo "$SITE already has a certificate; leaving it as it is."
else
  sed "s/__DOMAIN__/${DOMAIN}/g" "$HERE/nginx/secondline-cms.conf" > "$SITE"
fi
ln -sf "$SITE" /etc/nginx/sites-enabled/secondline-cms
rm -f /etc/nginx/sites-enabled/default

nginx -t
systemctl reload nginx

certbot --nginx --non-interactive --agree-tos --redirect -m "$EMAIL" -d "$DOMAIN"
systemctl reload nginx

echo "Nginx serves https://${DOMAIN} (renewal runs automatically: systemctl list-timers | grep certbot)."
