#!/bin/bash
# Put Fuel Dispatch on the public internet with HTTPS. Phones do not need Tailscale.
# Usage:
#   sudo DOMAIN=yourname.duckdns.org DUCKDNS_TOKEN=xxxxx bash /opt/fuel-dispatch/install-public.sh
# Or with a domain you already own:
#   sudo DOMAIN=dispatch.yourcompany.com bash /opt/fuel-dispatch/install-public.sh
set -euo pipefail

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

DOMAIN="${DOMAIN:-}"
DUCKDNS_TOKEN="${DUCKDNS_TOKEN:-}"
DUCKDNS_SUBDOMAIN="${DUCKDNS_SUBDOMAIN:-}"

if [ -z "$DOMAIN" ] && [ -n "$DUCKDNS_SUBDOMAIN" ]; then
  DOMAIN="${DUCKDNS_SUBDOMAIN}.duckdns.org"
fi

if [ -z "$DOMAIN" ]; then
  echo "Fuel Dispatch needs a hostname for HTTPS (free is fine)."
  echo
  echo "1. Open https://www.duckdns.org and sign in (Google is fine)."
  echo "2. Create a subdomain, e.g. myfueldispatch"
  echo "3. Set the IPv4 address to this Droplet's public IP."
  echo "4. Copy the token from the DuckDNS page."
  echo "5. Run:"
  echo "     sudo DOMAIN=myfueldispatch.duckdns.org DUCKDNS_TOKEN=your-token bash /opt/fuel-dispatch/install-public.sh"
  exit 1
fi

echo "Public hostname: $DOMAIN"

if [ -n "$DUCKDNS_TOKEN" ]; then
  SUB="${DUCKDNS_SUBDOMAIN:-${DOMAIN%%.duckdns.org}}"
  echo "Updating DuckDNS..."
  curl -fsS "https://www.duckdns.org/update?domains=${SUB}&token=${DUCKDNS_TOKEN}&ip=" || true
  mkdir -p /etc/fuel-dispatch
  cat >/etc/fuel-dispatch/duckdns-update.sh <<EOF
#!/bin/bash
curl -fsS "https://www.duckdns.org/update?domains=${SUB}&token=${DUCKDNS_TOKEN}&ip=" >/dev/null
EOF
  chmod +x /etc/fuel-dispatch/duckdns-update.sh
  cat >/etc/systemd/system/duckdns.service <<EOF
[Unit]
Description=Update DuckDNS IP
[Service]
Type=oneshot
ExecStart=/etc/fuel-dispatch/duckdns-update.sh
EOF
  cat >/etc/systemd/system/duckdns.timer <<EOF
[Unit]
Description=Update DuckDNS every 10 minutes
[Timer]
OnBootSec=30sec
OnUnitActiveSec=10min
[Install]
WantedBy=timers.target
EOF
  systemctl daemon-reload
  systemctl enable --now duckdns.timer
fi

if ! command -v caddy >/dev/null 2>&1; then
  echo "Installing Caddy..."
  apt-get update -y
  apt-get install -y debian-keyring debian-archive-keyring apt-transport-https curl gpg
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
  apt-get update -y
  apt-get install -y caddy
fi

cat >/etc/caddy/Caddyfile <<EOF
${DOMAIN} {
  encode gzip
  request_body {
    max_size 80MB
  }
  header {
    Strict-Transport-Security "max-age=31536000; includeSubDomains"
    X-Content-Type-Options nosniff
    Referrer-Policy same-origin
  }
  reverse_proxy 127.0.0.1:8080
}
EOF

# Keep Node only on localhost so 8080 is not on the public internet.
if [ -f /etc/systemd/system/fuel-dispatch.service ]; then
  python3 - <<'PY'
from pathlib import Path
p = Path("/etc/systemd/system/fuel-dispatch.service")
t = p.read_text()
if "HOST=127.0.0.1" not in t:
    t = t.replace("Environment=PORT=8080", "Environment=PORT=8080\nEnvironment=HOST=127.0.0.1")
    p.write_text(t)
PY
  systemctl daemon-reload
  systemctl restart fuel-dispatch
fi

systemctl enable --now caddy
systemctl reload caddy || systemctl restart caddy

if command -v ufw >/dev/null 2>&1; then
  ufw allow 80/tcp
  ufw allow 443/tcp
  ufw delete allow 8080 2>/dev/null || true
  ufw delete allow 8080/tcp 2>/dev/null || true
fi

echo
echo "Fuel Dispatch is public at:"
echo "  https://${DOMAIN}"
echo "  https://${DOMAIN}/android"
echo
echo "On the phone: install the APK, enter https://${DOMAIN} and Connect."
echo "Office PCs: same address in Chrome. No Tailscale."
echo "Sign in with your Fuel Dispatch username and password."
