#!/bin/bash
# Create and configure a permanent Cloudflare tunnel for the Teams webhook.
# Run after: cloudflared tunnel login
set -euo pipefail

TUNNEL_NAME="exult-teams"
HOSTNAME="teams-bot.exulthealthcare.com"
LOCAL_PORT="${MSTEAMS_WEBHOOK_PORT:-3978}"
CONFIG_DIR="$HOME/.cloudflared"

# Check login
if [ ! -f "$CONFIG_DIR/cert.pem" ]; then
  echo "ERROR: Run 'cloudflared tunnel login' first"
  exit 1
fi

# Create tunnel if it doesn't exist
if ! cloudflared tunnel list | grep -q "$TUNNEL_NAME"; then
  echo "Creating tunnel: $TUNNEL_NAME"
  cloudflared tunnel create "$TUNNEL_NAME"
else
  echo "Tunnel $TUNNEL_NAME already exists"
fi

# Get tunnel UUID
TUNNEL_ID=$(cloudflared tunnel list --output json | /Users/Work/.bun/bin/bun -e '
  const data = JSON.parse(await Bun.stdin.text());
  const tunnel = data.find(t => t.name === "'"$TUNNEL_NAME"'");
  if (tunnel) process.stdout.write(tunnel.id);
')

if [ -z "$TUNNEL_ID" ]; then
  echo "ERROR: Could not find tunnel ID"
  exit 1
fi

echo "Tunnel ID: $TUNNEL_ID"

# Write config
cat > "$CONFIG_DIR/config.yml" <<EOF
tunnel: $TUNNEL_ID
credentials-file: $CONFIG_DIR/$TUNNEL_ID.json

ingress:
  - hostname: $HOSTNAME
    service: http://localhost:$LOCAL_PORT
  - service: http_status:404
EOF

echo "Config written to $CONFIG_DIR/config.yml"

# Create DNS route
echo "Creating DNS route: $HOSTNAME -> $TUNNEL_NAME"
cloudflared tunnel route dns "$TUNNEL_NAME" "$HOSTNAME" 2>/dev/null || echo "(DNS route may already exist)"

echo ""
echo "Done! Update the Teams bot messaging endpoint to:"
echo "  https://$HOSTNAME/api/messages"
echo ""
echo "Start the tunnel with: cloudflared tunnel run $TUNNEL_NAME"
echo "Or load the LaunchAgent: launchctl load ~/Library/LaunchAgents/com.exult.teams-tunnel.plist"
