#!/bin/bash
# Complete the domain + nginx + SSL setup
# Run this AFTER DNS is configured and propagated
#
# Prerequisites:
# 1. DNS A record: rivet.rateright.com.au → 134.199.153.159
# 2. nginx installed (already done)
# 3. certbot installed (already done)

set -e

DOMAIN="rivet.rateright.com.au"
VPS_IP="134.199.153.159"
CLAWDBOT_CONFIG="$HOME/.clawdbot/clawdbot.json"
NGINX_CONF="/etc/nginx/sites-available/$DOMAIN"
SETUP_DIR="/home/ccuser/rateright-growth/rivet/setup/nginx-ssl"

echo "=== Domain + nginx + SSL Setup ==="
echo "Domain: $DOMAIN"
echo "VPS IP: $VPS_IP"
echo ""

# Step 1: Verify DNS
echo "Step 1: Checking DNS propagation..."
RESOLVED_IP=$(dig +short $DOMAIN 2>/dev/null | head -1)

if [ "$RESOLVED_IP" != "$VPS_IP" ]; then
    echo "ERROR: DNS not configured correctly"
    echo "  Expected: $VPS_IP"
    echo "  Got: $RESOLVED_IP"
    echo ""
    echo "Please add this DNS record:"
    echo "  Type: A"
    echo "  Name: rivet"
    echo "  Value: $VPS_IP"
    echo ""
    echo "Then wait for propagation (usually 5-15 minutes) and run this script again."
    exit 1
fi

echo "  ✓ DNS resolves to $VPS_IP"
echo ""

# Step 2: Install nginx config
echo "Step 2: Installing nginx configuration..."
if [ ! -f "$NGINX_CONF" ]; then
    cp "$SETUP_DIR/rivet.rateright.com.au.conf" "$NGINX_CONF"
    echo "  ✓ Copied config to $NGINX_CONF"
else
    echo "  ✓ Config already exists"
fi

# Enable site
if [ ! -L "/etc/nginx/sites-enabled/$DOMAIN" ]; then
    ln -sf "$NGINX_CONF" "/etc/nginx/sites-enabled/$DOMAIN"
    echo "  ✓ Enabled site"
else
    echo "  ✓ Site already enabled"
fi

# Remove default site if it exists
if [ -L "/etc/nginx/sites-enabled/default" ]; then
    rm "/etc/nginx/sites-enabled/default"
    echo "  ✓ Removed default site"
fi

# Test nginx config
nginx -t || { echo "ERROR: nginx config test failed"; exit 1; }
echo "  ✓ nginx config valid"

# Reload nginx (without SSL first, to serve HTTP challenge)
systemctl reload nginx
echo "  ✓ nginx reloaded"
echo ""

# Step 3: Obtain SSL certificate
echo "Step 3: Obtaining SSL certificate..."
if [ -d "/etc/letsencrypt/live/$DOMAIN" ]; then
    echo "  ✓ Certificate already exists"
else
    certbot --nginx -d $DOMAIN --non-interactive --agree-tos --email admin@rateright.com.au --redirect
    echo "  ✓ Certificate obtained"
fi
echo ""

# Step 4: Verify HTTPS works
echo "Step 4: Verifying HTTPS..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "https://$DOMAIN/health" 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "404" ]; then
    echo "  ✓ HTTPS working (HTTP $HTTP_CODE)"
else
    echo "  ⚠ HTTPS check returned HTTP $HTTP_CODE (may be OK if webhook not ready)"
fi
echo ""

# Step 5: Update Clawdbot config
echo "Step 5: Updating Clawdbot configuration..."
if [ -f "$CLAWDBOT_CONFIG" ]; then
    # Check if already updated
    if grep -q "rivet.rateright.com.au" "$CLAWDBOT_CONFIG"; then
        echo "  ✓ Config already updated"
    else
        # Use jq to update the publicUrl in voice-call plugin
        if command -v jq &> /dev/null; then
            TMP_FILE=$(mktemp)
            jq '.plugins.entries."voice-call".config.outbound.webhook.publicUrl = "https://rivet.rateright.com.au/voice/webhook"' "$CLAWDBOT_CONFIG" > "$TMP_FILE"
            mv "$TMP_FILE" "$CLAWDBOT_CONFIG"
            echo "  ✓ Updated voice-call webhook URL"
        else
            echo "  ⚠ jq not installed - manual config update needed"
            echo "    Update publicUrl to: https://rivet.rateright.com.au/voice/webhook"
        fi
    fi
else
    echo "  ⚠ Clawdbot config not found at $CLAWDBOT_CONFIG"
fi
echo ""

# Step 6: Restart Clawdbot
echo "Step 6: Restarting Clawdbot gateway..."
if command -v clawdbot &> /dev/null; then
    clawdbot gateway restart || echo "  ⚠ Gateway restart command failed - may need manual restart"
    echo "  ✓ Gateway restarted"
else
    echo "  ⚠ clawdbot command not found - may need manual restart"
fi
echo ""

# Step 7: Disable Tailscale Funnel (optional)
echo "Step 7: Tailscale Funnel..."
echo "  The Tailscale Funnel is still active. You can disable it with:"
echo "    tailscale funnel off"
echo "  (Wait until everything is confirmed working first)"
echo ""

# Done
echo "=== Setup Complete ==="
echo ""
echo "New webhook URL: https://$DOMAIN/voice/webhook"
echo ""
echo "Next steps:"
echo "1. Test voice calls to verify webhooks work"
echo "2. Update any external services using the old Tailscale URL"
echo "3. Once confirmed, run: tailscale funnel off"
echo ""
echo "Certificate auto-renewal is handled by certbot timer."
echo "Check with: systemctl status certbot.timer"
