#!/usr/bin/env bash
# Setup Cloudflare Tunnel for Miracles In Motion
# Usage: ./setup-cloudflare-tunnel-mim.sh <tunnel-token>

set -euo pipefail

TUNNEL_TOKEN="${1:-}"

if [[ -z "$TUNNEL_TOKEN" ]]; then
    echo "Usage: $0 <tunnel-token>"
    echo ""
    echo "To get the tunnel token:"
    echo "1. Go to https://one.dash.cloudflare.com"
    echo "2. Navigate to Zero Trust > Networks > Tunnels"
    echo "3. Create a tunnel named 'mim4u-tunnel'"
    echo "4. Copy the tunnel token"
    exit 1
fi

PROXMOX_HOST="192.168.11.12"
CONTAINER_ID="7810"

echo "Setting up Cloudflare Tunnel for Miracles In Motion..."
echo ""

# Update service with tunnel token
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct exec $CONTAINER_ID -- bash" <<SERVICESCRIPT
cat > /etc/systemd/system/cloudflared-mim.service <<EOF
[Unit]
Description=Cloudflare Tunnel for Miracles In Motion
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/cloudflared tunnel --config /etc/cloudflared/config.yml run
Restart=always
RestartSec=10
Environment="TUNNEL_TOKEN=$TUNNEL_TOKEN"

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable cloudflared-mim
systemctl start cloudflared-mim
systemctl status cloudflared-mim --no-pager | head -10
SERVICESCRIPT

echo ""
echo "✅ Cloudflare Tunnel configured and started!"
echo ""
echo "Next steps:"
echo "1. Verify tunnel is running: ssh root@$PROXMOX_HOST 'pct exec $CONTAINER_ID -- systemctl status cloudflared-mim'"
echo "2. Check tunnel logs: ssh root@$PROXMOX_HOST 'pct exec $CONTAINER_ID -- journalctl -u cloudflared-mim -f'"
echo "3. Test domain: curl -I https://mim4u.org"
