#!/bin/bash
# Install Cloudflare tunnel using token
# Token is for tunnel: 10ab22da-8ea3-4e2e-a896-27ece2211a05 (shared tunnel)

set -e

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

echo "═══════════════════════════════════════════════════════════"
echo "  Install Shared Tunnel with Token"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Tunnel ID: ${TUNNEL_ID}"
echo "Target 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 "This script needs to be run:"
    echo "  1. From a machine on 192.168.11.0/24 network, OR"
    echo "  2. Via SSH tunnel (after running setup_ssh_tunnel.sh), OR"
    echo "  3. Directly on the Proxmox host"
    echo ""
    echo "Alternative: Install directly in container"
    echo "  ssh root@${PROXMOX_HOST}"
    echo "  pct exec ${VMID} -- bash"
    echo "  # Then run the installation commands manually"
    echo ""
    
    # Generate manual installation instructions
    cat > /tmp/tunnel-install-manual.md << 'MANUAL_EOF'
# Manual Tunnel Installation

## Step 1: Access Container

```bash
ssh root@192.168.11.12
pct exec 102 -- bash
```

## Step 2: Install cloudflared (if not installed)

```bash
apt update
apt install -y cloudflared
```

## Step 3: Install Tunnel Service with Token

```bash
cloudflared service install eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiMTBhYjIyZGEtOGVhMy00ZTJlLWE4OTYtMjdlY2UyMjExYTA1IiwicyI6IlptRXlOMkkyTVRrdE1EZzFNeTAwTkRBNExXSXhaalF0Wm1KaE5XVmpaVEEzTVdGbCJ9
```

## Step 4: Configure Ingress Rules

The token installation creates a basic service. You need to configure ingress rules for all 9 hostnames.

### Option A: Via Cloudflare Dashboard (Recommended)

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 9 hostnames (see below)

### Option B: Manual Config File

Create `/etc/cloudflared/config.yml`:

```yaml
tunnel: 10ab22da-8ea3-4e2e-a896-27ece2211a05
credentials-file: /root/.cloudflared/<tunnel-id>.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
```

## Step 5: Restart Service

```bash
systemctl restart cloudflared
systemctl status cloudflared
```

## Step 6: Verify

```bash
# Check service status
systemctl status cloudflared

# Check logs
journalctl -u cloudflared -f

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

MANUAL_EOF

    echo "📄 Manual instructions saved to: /tmp/tunnel-install-manual.md"
    exit 1
fi

echo "✅ Connected to container"
echo ""

# Step 1: Check cloudflared installation
echo "Step 1: Checking cloudflared installation..."
if ! ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- which cloudflared" >/dev/null 2>&1; then
    echo "⚠️  cloudflared not installed. Installing..."
    ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash -c 'apt update && apt install -y cloudflared'" || {
        echo "❌ Failed to install cloudflared"
        exit 1
    }
    echo "✅ cloudflared installed"
else
    echo "✅ cloudflared is installed"
fi
echo ""

# Step 2: Install tunnel service with token
echo "Step 2: Installing tunnel service with token..."
echo "This will create a systemd service for the tunnel."
echo ""

ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash -c 'cloudflared service install ${TUNNEL_TOKEN}'" || {
    echo "⚠️  Service install may have failed or service already exists"
    echo "   Continuing with configuration..."
}
echo ""

# Step 3: Create configuration file
echo "Step 3: Creating tunnel configuration..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash" << 'CONFIG_EOF'
cat > /etc/cloudflared/config.yml << 'YAML_EOF'
tunnel: 10ab22da-8ea3-4e2e-a896-27ece2211a05
credentials-file: /root/.cloudflared/10ab22da-8ea3-4e2e-a896-27ece2211a05.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
YAML_EOF

chmod 600 /etc/cloudflared/config.yml
echo "✅ Configuration file created"
CONFIG_EOF

echo ""

# Step 4: Restart service
echo "Step 4: Restarting tunnel service..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl daemon-reload"
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl restart cloudflared" || \
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl start cloudflared"
sleep 3
echo "✅ Service restarted"
echo ""

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

# Step 6: Show logs
echo "Step 6: Recent logs (last 20 lines)..."
echo ""
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- journalctl -u cloudflared -n 20 --no-pager" || true
echo ""

echo "═══════════════════════════════════════════════════════════"
echo "  Installation Complete"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Next steps:"
echo "  1. Wait 1-2 minutes for tunnel to connect"
echo "  2. Check Cloudflare Dashboard - tunnel should show HEALTHY"
echo "  3. Test endpoints:"
echo "     curl -I https://dbis-admin.d-bis.org"
echo "     curl -I https://rpc-http-pub.d-bis.org"
echo ""
echo "If tunnel is still DOWN:"
echo "  - Check logs: ssh root@${PROXMOX_HOST} 'pct exec ${VMID} -- journalctl -u cloudflared -f'"
echo "  - Verify credentials file exists: /root/.cloudflared/10ab22da-8ea3-4e2e-a896-27ece2211a05.json"
echo "  - Verify Nginx is accessible at 192.168.11.21:80"
echo ""
