#!/usr/bin/env bash
# Quick install using a single token (for ml110 tunnel)
# Usage: ./quick-install-token.sh <token>

set -euo pipefail

TOKEN="${1:-}"

if [[ -z "$TOKEN" ]]; then
    echo "Usage: $0 <token>"
    echo ""
    echo "Example:"
    echo "  $0 eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiY2NkNzE1MGEtOTg4MS00YjhjLWExMDUtOWI0ZWFkNmU2OWEyIiwicyI6IkZtems1ZDdUWDR0OW03Q0huVU9DYTYyTFdiQVFPZkZKa2duRHhQdExkZldKNGVvTHgyckw5K2szVCs5N0lFTFFoNGdHdHZLbzNacGZpNmI4TkdxdUlnPT0ifQ=="
    exit 1
fi

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID="${VMID:-102}"

# Decode token
TOKEN_DATA=$(echo "$TOKEN" | base64 -d)
TUNNEL_ID=$(echo "$TOKEN_DATA" | jq -r '.t')
ACCOUNT_TAG=$(echo "$TOKEN_DATA" | jq -r '.a')
TUNNEL_SECRET=$(echo "$TOKEN_DATA" | jq -r '.s')

echo "Token decoded:"
echo "  Tunnel ID: $TUNNEL_ID"
echo "  Account Tag: $ACCOUNT_TAG"
echo ""

# Determine tunnel name based on ID
case "$TUNNEL_ID" in
    "ccd7150a-9881-4b8c-a105-9b4ead6e69a2")
        TUNNEL_KEY="ml110"
        TUNNEL_NAME="tunnel-ml110"
        HOSTNAME="ml110-01.d-bis.org"
        TARGET="https://192.168.11.10:8006"
        ;;
    "4481af8f-b24c-4cd3-bdd5-f562f4c97df4")
        TUNNEL_KEY="r630-01"
        TUNNEL_NAME="tunnel-r630-01"
        HOSTNAME="r630-01.d-bis.org"
        TARGET="https://192.168.11.11:8006"
        ;;
    "0876f12b-64d7-4927-9ab3-94cb6cf48af9")
        TUNNEL_KEY="r630-02"
        TUNNEL_NAME="tunnel-r630-02"
        HOSTNAME="r630-02.d-bis.org"
        TARGET="https://192.168.11.12:8006"
        ;;
    *)
        echo "Unknown tunnel ID: $TUNNEL_ID"
        exit 1
        ;;
esac

echo "Installing for: $TUNNEL_NAME"
echo "  Hostname: $HOSTNAME"
echo "  Target: $TARGET"
echo ""

# Create credentials file
CREDS_JSON=$(jq -n \
    --arg account "$ACCOUNT_TAG" \
    --arg secret "$TUNNEL_SECRET" \
    --arg id "$TUNNEL_ID" \
    --arg name "$TUNNEL_NAME" \
    '{
        AccountTag: $account,
        TunnelSecret: $secret,
        TunnelID: $id,
        TunnelName: $name
    }')

# Create config file
CONFIG_YML="tunnel: $TUNNEL_ID
credentials-file: /etc/cloudflared/credentials-${TUNNEL_KEY}.json

ingress:
  - hostname: $HOSTNAME
    service: $TARGET
    originRequest:
      noHappyEyeballs: true
      connectTimeout: 30s
      tcpKeepAlive: 30s
      keepAliveConnections: 100
      keepAliveTimeout: 90s
      disableChunkedEncoding: true
      noTLSVerify: true
  - service: http_status:404"

# Copy to container
echo "Copying files to VMID $VMID..."

# Credentials
echo "$CREDS_JSON" > /tmp/credentials-${TUNNEL_KEY}.json
scp /tmp/credentials-${TUNNEL_KEY}.json root@${PROXMOX_HOST}:/tmp/ >/dev/null 2>&1
ssh root@${PROXMOX_HOST} "pct push $VMID /tmp/credentials-${TUNNEL_KEY}.json /etc/cloudflared/credentials-${TUNNEL_KEY}.json" >/dev/null 2>&1
ssh root@${PROXMOX_HOST} "pct exec $VMID -- chmod 600 /etc/cloudflared/credentials-${TUNNEL_KEY}.json"

# Config
echo "$CONFIG_YML" > /tmp/tunnel-${TUNNEL_KEY}.yml
scp /tmp/tunnel-${TUNNEL_KEY}.yml root@${PROXMOX_HOST}:/tmp/ >/dev/null 2>&1
ssh root@${PROXMOX_HOST} "pct push $VMID /tmp/tunnel-${TUNNEL_KEY}.yml /etc/cloudflared/tunnel-${TUNNEL_KEY}.yml" >/dev/null 2>&1

# Service file
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TUNNELS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
SERVICE_FILE="$TUNNELS_DIR/systemd/cloudflared-${TUNNEL_KEY}.service"

if [ -f "$SERVICE_FILE" ]; then
    scp "$SERVICE_FILE" root@${PROXMOX_HOST}:/tmp/ >/dev/null 2>&1
    ssh root@${PROXMOX_HOST} "pct push $VMID /tmp/cloudflared-${TUNNEL_KEY}.service /etc/systemd/system/cloudflared-${TUNNEL_KEY}.service" >/dev/null 2>&1
    ssh root@${PROXMOX_HOST} "pct exec $VMID -- systemctl daemon-reload"
    ssh root@${PROXMOX_HOST} "pct exec $VMID -- systemctl enable cloudflared-${TUNNEL_KEY}.service"
    echo "✓ Service installed and enabled"
fi

# Cleanup
rm -f /tmp/credentials-${TUNNEL_KEY}.json /tmp/tunnel-${TUNNEL_KEY}.yml

echo ""
echo "✓ Installation complete for $TUNNEL_NAME"
echo ""
echo "Start service:"
echo "  ssh root@${PROXMOX_HOST} 'pct exec $VMID -- systemctl start cloudflared-${TUNNEL_KEY}'"

