#!/bin/bash
# Fix shared Cloudflare tunnel configuration
# Resolves DNS conflicts for tunnel 10ab22da-8ea3-4e2e-a896-27ece2211a05

set -e

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"
VMID="${VMID:-102}"
TUNNEL_ID="10ab22da-8ea3-4e2e-a896-27ece2211a05"
NGINX_TARGET="192.168.11.21:80"

echo "═══════════════════════════════════════════════════════════"
echo "  Fix Shared Cloudflare Tunnel Configuration"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Tunnel ID: ${TUNNEL_ID}"
echo "Target: http://${NGINX_TARGET}"
echo "Container: VMID ${VMID} on ${PROXMOX_HOST}"
echo ""

# Check if we can connect
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "pct exec ${VMID} -- echo 'Connected'" 2>/dev/null; then
    echo "❌ Cannot connect to VMID ${VMID} on ${PROXMOX_HOST}"
    echo ""
    echo "═══════════════════════════════════════════════════════════"
    echo "  Connection Failed - Alternative Methods"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "Your machine is on a different network segment."
    echo "Use one of these methods:"
    echo ""
    echo "Method 1: Use SSH Tunnel First"
    echo "  ./setup_ssh_tunnel.sh"
    echo "  # Then in another terminal:"
    echo "  PROXMOX_HOST=localhost ./fix-shared-tunnel.sh"
    echo ""
    echo "Method 2: Run from Proxmox Network"
    echo "  Copy this script to a machine on 192.168.11.0/24 network"
    echo "  Then run: ./fix-shared-tunnel.sh"
    echo ""
    echo "Method 3: Manual Configuration"
    echo "  See: DNS_CONFLICT_RESOLUTION.md for manual steps"
    echo ""
    echo "Method 4: Use Cloudflare Dashboard"
    echo "  Configure tunnel via: https://one.dash.cloudflare.com/"
    echo "  Zero Trust → Networks → Tunnels → Configure"
    echo ""
    
    # Generate configuration files for manual deployment
    echo "Generating configuration files for manual deployment..."
    mkdir -p /tmp/tunnel-fix-${TUNNEL_ID}
    
    cat > /tmp/tunnel-fix-${TUNNEL_ID}/tunnel-services.yml << 'CONFIG_EOF'
tunnel: 10ab22da-8ea3-4e2e-a896-27ece2211a05
credentials-file: /etc/cloudflared/credentials-services.json

ingress:
  - hostname: dbis-admin.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: dbis-admin.d-bis.org
  - hostname: dbis-api.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: dbis-api.d-bis.org
  - hostname: dbis-api-2.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: dbis-api-2.d-bis.org
  - hostname: mim4u.org.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: mim4u.org.d-bis.org
  - hostname: www.mim4u.org.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: www.mim4u.org.d-bis.org
  - hostname: rpc-http-prv.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-http-prv.d-bis.org
  - hostname: rpc-http-pub.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-http-pub.d-bis.org
  - hostname: rpc-ws-prv.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-ws-prv.d-bis.org
  - hostname: rpc-ws-pub.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-ws-pub.d-bis.org
  - service: http_status:404

metrics: 127.0.0.1:9090
loglevel: info
gracePeriod: 30s
CONFIG_EOF

    cat > /tmp/tunnel-fix-${TUNNEL_ID}/cloudflared-services.service << 'SERVICE_EOF'
[Unit]
Description=Cloudflare Tunnel for Services (RPC, API, Admin, MIM4U)
After=network.target

[Service]
TimeoutStartSec=0
Type=notify
ExecStart=/usr/local/bin/cloudflared --config /etc/cloudflared/tunnel-services.yml tunnel run
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
SERVICE_EOF

    cat > /tmp/tunnel-fix-${TUNNEL_ID}/DEPLOY_INSTRUCTIONS.md << 'INST_EOF'
# Manual Deployment Instructions

## Files Generated

- `tunnel-services.yml` - Tunnel configuration
- `cloudflared-services.service` - Systemd service file
- `DEPLOY_INSTRUCTIONS.md` - This file

## Deployment Steps

### Option A: From Proxmox Host (192.168.11.12)

```bash
# 1. Copy files to Proxmox host
scp tunnel-services.yml root@192.168.11.12:/tmp/
scp cloudflared-services.service root@192.168.11.12:/tmp/

# 2. SSH to Proxmox host
ssh root@192.168.11.12

# 3. Copy files into container
pct push 102 /tmp/tunnel-services.yml /etc/cloudflared/tunnel-services.yml
pct push 102 /tmp/cloudflared-services.service /etc/systemd/system/cloudflared-services.service

# 4. Set permissions
pct exec 102 -- chmod 600 /etc/cloudflared/tunnel-services.yml

# 5. Reload systemd and start
pct exec 102 -- systemctl daemon-reload
pct exec 102 -- systemctl enable cloudflared-services.service
pct exec 102 -- systemctl start cloudflared-services.service

# 6. Check status
pct exec 102 -- systemctl status cloudflared-services.service
```

### Option B: Direct Container Access

If you have direct access to the container:

```bash
# 1. Copy files into container
# (Use pct push or copy manually)

# 2. Inside container:
chmod 600 /etc/cloudflared/tunnel-services.yml
systemctl daemon-reload
systemctl enable cloudflared-services.service
systemctl start cloudflared-services.service
systemctl status cloudflared-services.service
```

### Option C: Via Cloudflare Dashboard

1. Go to: https://one.dash.cloudflare.com/
2. Zero Trust → Networks → Tunnels
3. Find tunnel: `10ab22da-8ea3-4e2e-a896-27ece2211a05`
4. Click Configure
5. Add all hostnames as shown in tunnel-services.yml
6. Save configuration

## Verification

After deployment:

```bash
# Check service status
pct exec 102 -- systemctl status cloudflared-services.service

# Check logs
pct exec 102 -- journalctl -u cloudflared-services -f

# Test endpoints
curl -I https://dbis-admin.d-bis.org
curl -I https://rpc-http-pub.d-bis.org
```

## Important Notes

- Ensure credentials file exists: `/etc/cloudflared/credentials-services.json`
- Verify Nginx is accessible at `192.168.11.21:80`
- Check tunnel status in Cloudflare dashboard
INST_EOF

    echo "✅ Configuration files generated in: /tmp/tunnel-fix-${TUNNEL_ID}/"
    echo ""
    echo "Files created:"
    echo "  - tunnel-services.yml (tunnel configuration)"
    echo "  - cloudflared-services.service (systemd service)"
    echo "  - DEPLOY_INSTRUCTIONS.md (deployment guide)"
    echo ""
    echo "Next steps:"
    echo "  1. Review files in /tmp/tunnel-fix-${TUNNEL_ID}/"
    echo "  2. Follow DEPLOY_INSTRUCTIONS.md"
    echo "  3. Or use Cloudflare Dashboard method"
    echo ""
    
    exit 1
fi

echo "✅ Connected to container"
echo ""

# Create tunnel configuration
echo "Creating tunnel configuration..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash" << 'TUNNEL_CONFIG'
cat > /etc/cloudflared/tunnel-services.yml << 'EOF'
tunnel: 10ab22da-8ea3-4e2e-a896-27ece2211a05
credentials-file: /etc/cloudflared/credentials-services.json

ingress:
  # Admin Interface
  - hostname: dbis-admin.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: dbis-admin.d-bis.org

  # API Endpoints
  - hostname: dbis-api.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: dbis-api.d-bis.org

  - hostname: dbis-api-2.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: dbis-api-2.d-bis.org

  # MIM4U Services
  - hostname: mim4u.org.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: mim4u.org.d-bis.org

  - hostname: www.mim4u.org.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: www.mim4u.org.d-bis.org

  # RPC Endpoints - HTTP
  - hostname: rpc-http-prv.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-http-prv.d-bis.org

  - hostname: rpc-http-pub.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-http-pub.d-bis.org

  # RPC Endpoints - WebSocket
  - hostname: rpc-ws-prv.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-ws-prv.d-bis.org

  - hostname: rpc-ws-pub.d-bis.org
    service: http://192.168.11.21:80
    originRequest:
      httpHostHeader: rpc-ws-pub.d-bis.org

  # Catch-all (MUST be last)
  - service: http_status:404

# Metrics
metrics: 127.0.0.1:9090

# Logging
loglevel: info

# Grace period
gracePeriod: 30s
EOF

chmod 600 /etc/cloudflared/tunnel-services.yml
echo "✅ Configuration file created"
TUNNEL_CONFIG

# Create systemd service
echo "Creating systemd service..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash" << 'SERVICE_CONFIG'
cat > /etc/systemd/system/cloudflared-services.service << 'EOF'
[Unit]
Description=Cloudflare Tunnel for Services (RPC, API, Admin, MIM4U)
After=network.target

[Service]
TimeoutStartSec=0
Type=notify
ExecStart=/usr/local/bin/cloudflared --config /etc/cloudflared/tunnel-services.yml tunnel run
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

echo "✅ Service file created"
SERVICE_CONFIG

# Reload systemd and enable service
echo "Enabling and starting service..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl daemon-reload"
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl enable cloudflared-services.service" || echo "⚠️  Service may already be enabled"
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl restart cloudflared-services.service" || ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl start cloudflared-services.service"

# Wait a moment
sleep 3

# Check status
echo ""
echo "Checking service status..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl status cloudflared-services.service --no-pager -l" || true

echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  Configuration Complete"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Next steps:"
echo "  1. Verify credentials file exists:"
echo "     ssh root@${PROXMOX_HOST} 'pct exec ${VMID} -- ls -la /etc/cloudflared/credentials-services.json'"
echo ""
echo "  2. Check tunnel logs:"
echo "     ssh root@${PROXMOX_HOST} 'pct exec ${VMID} -- journalctl -u cloudflared-services -f'"
echo ""
echo "  3. Test hostnames:"
echo "     curl -I https://dbis-admin.d-bis.org"
echo "     curl -I https://rpc-http-pub.d-bis.org"
echo ""
echo "  4. Update TTL values in Cloudflare Dashboard:"
echo "     DNS → Records → Change TTL from 1 to 300 (or Auto)"
echo ""
