#!/bin/bash
# Deploy client.gigafibre.ca portal route to Traefik
#
# Usage: bash deploy-portal.sh
# Requires: SSH access to 96.125.196.67

set -e

SERVER="root@96.125.196.67"
SSH_KEY="$HOME/.ssh/proxmox_vm"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Deploying client.gigafibre.ca portal route ==="

# 1. Copy Traefik dynamic route
echo "  → Copying Traefik config..."
scp -i "$SSH_KEY" "$SCRIPT_DIR/traefik-client-portal.yml" \
  "$SERVER:/opt/traefik/dynamic/client-portal.yml"

# 2. Verify Traefik picks it up (check logs for new route)
echo "  → Checking Traefik logs for route registration..."
ssh -i "$SSH_KEY" "$SERVER" 'sleep 2 && docker logs --tail 20 traefik 2>&1 | grep -i "client\|portal\|error" || echo "  (no portal-specific logs yet — normal on first load)"'

# 3. Verify TLS cert provisioning
echo "  → Checking TLS cert (Let's Encrypt will provision on first request)..."
echo "  → Try: curl -sI https://client.gigafibre.ca/login | head -5"

# 4. Quick connectivity test
echo ""
echo "  → Testing connectivity..."
STATUS=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://client.gigafibre.ca/login" 2>/dev/null || echo "000")
if [ "$STATUS" = "200" ]; then
  echo "  ✓ client.gigafibre.ca is live! (HTTP $STATUS)"
elif [ "$STATUS" = "000" ]; then
  echo "  ⏳ TLS cert not ready yet — Let's Encrypt needs a moment"
  echo "     Wait 30s and try: curl -sI https://client.gigafibre.ca/login"
else
  echo "  → HTTP $STATUS — check Traefik logs: docker logs --tail 50 traefik"
fi

echo ""
echo "=== Done ==="
echo ""
echo "Portal URL: https://client.gigafibre.ca"
echo "Login:      https://client.gigafibre.ca/login"
echo "Invoices:   https://client.gigafibre.ca/invoices"
echo "Profile:    https://client.gigafibre.ca/me"
echo ""
echo "Test user:  etl@exprotransit.com / TestPortal2026!"
