#!/usr/bin/env bash set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" SKILL_ROOT="$(dirname "$SCRIPT_DIR")" source "$SCRIPT_DIR/_common.sh" : "${CF_API_TOKEN:=}" : "${CF_ACCOUNT_ID:=}" : "${TUNNEL_NAME:=}" : "${CONFIG_DIR:=$SKILL_ROOT/outputs/config}" main() { confirm_gate cf_env_check [[ -n "$TUNNEL_NAME" ]] || die "TUNNEL_NAME is required." mkdir -p "$CONFIG_DIR" # List tunnels and locate by name log_info "Looking for existing tunnel: $TUNNEL_NAME" local list_json list_json="$(cloudflared tunnel --origincert /dev/null list --output json 2>/dev/null || true)" # If list command fails (often needs login), fall back to API call local tunnel_id="" if [[ -n "$list_json" ]]; then tunnel_id="$(echo "$list_json" | jq -r --arg n "$TUNNEL_NAME" '.[] | select(.name==$n) | .id' | head -n 1 || true)" fi if [[ -z "$tunnel_id" || "$tunnel_id" == "null" ]]; then log_warn "Tunnel not found via CLI list (or CLI not logged in). Creating tunnel via cloudflared..." # cloudflared tunnel create requires local credentials; this will prompt if needed. cloudflared tunnel create "$TUNNEL_NAME" # After creation, attempt list again list_json="$(cloudflared tunnel list --output json 2>/dev/null || true)" tunnel_id="$(echo "$list_json" | jq -r --arg n "$TUNNEL_NAME" '.[] | select(.name==$n) | .id' | head -n 1 || true)" fi [[ -n "$tunnel_id" && "$tunnel_id" != "null" ]] || die "Unable to determine tunnel id for $TUNNEL_NAME. Ensure cloudflared is authenticated." log_info "Tunnel id: $tunnel_id" # Snapshot tunnel info cat > "$CONFIG_DIR/tunnel.json" <