#!/usr/bin/env bash

ngrok_config_file() {
  echo "${NGROK_CONFIG_FILE:-$HOME/.config/ngrok/ngrok.yml}"
}

configure_ngrok_authtoken() {
  if [[ -z "${NGROK_AUTHTOKEN:-}" ]]; then
    return 0
  fi

  if [[ "${NGROK_AUTHTOKEN}" == "TU_TOKEN" || "${NGROK_AUTHTOKEN}" == "cambia-este-token" ]]; then
    echo "NGROK_AUTHTOKEN esta configurado con un placeholder." >&2
    echo "Reemplazalo por un token real de ngrok antes de levantar el tunel." >&2
    exit 1
  fi

  ngrok config add-authtoken "$NGROK_AUTHTOKEN" >/dev/null
}

assert_valid_ngrok_config() {
  local config_file
  config_file="$(ngrok_config_file)"

  if [[ ! -f "$config_file" ]]; then
    echo "No encuentro la configuracion de ngrok en $config_file." >&2
    echo "Configura NGROK_AUTHTOKEN o ejecuta: ngrok config add-authtoken <tu_token>" >&2
    exit 1
  fi

  if grep -Eq 'authtoken:\s*(TU_TOKEN|cambia-este-token|cambia-esta-clave|$)' "$config_file"; then
    echo "La configuracion de ngrok tiene un authtoken placeholder en $config_file." >&2
    echo "Necesitas cargar un token real para que el tunel funcione." >&2
    exit 1
  fi
}
