#!/usr/bin/env bash
# Load credentials from tunnel-credentials.json and save them

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TUNNELS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

CREDS_FILE="$TUNNELS_DIR/tunnel-credentials.json"

if [ ! -f "$CREDS_FILE" ]; then
    log_error "Credentials file not found: $CREDS_FILE"
    log_info "Run ./scripts/automate-cloudflare-setup.sh first"
    exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
    log_error "jq is required"
    exit 1
fi

log_info "Loading credentials from: $CREDS_FILE"

# Load and save each tunnel's credentials
for tunnel_name in ml110 r630-01 r630-02; do
    # Handle tunnel names with hyphens by using array notation
    if [[ "$tunnel_name" == "r630-01" ]] || [[ "$tunnel_name" == "r630-02" ]]; then
        tunnel_id=$(jq -r ".[\"${tunnel_name}\"].id // empty" "$CREDS_FILE")
        tunnel_token=$(jq -r ".[\"${tunnel_name}\"].token // empty" "$CREDS_FILE")
    else
        tunnel_id=$(jq -r ".${tunnel_name}.id // empty" "$CREDS_FILE")
        tunnel_token=$(jq -r ".${tunnel_name}.token // empty" "$CREDS_FILE")
    fi
    
    if [[ -z "$tunnel_id" ]] || [[ -z "$tunnel_token" ]]; then
        log_warn "Missing credentials for $tunnel_name"
        continue
    fi
    
    log_info "Saving credentials for $tunnel_name..."
    if "$SCRIPT_DIR/save-tunnel-credentials.sh" "$tunnel_name" "$tunnel_id" "$tunnel_token"; then
        log_success "Credentials saved for $tunnel_name"
    else
        log_error "Failed to save credentials for $tunnel_name"
    fi
    echo ""
done

log_success "All credentials saved!"
log_info "Next: Start services with: systemctl start cloudflared-*"

