#!/usr/bin/env bash
# Conecta este equipo a Tailscale a través del túnel cdn-static.ditotabs.me.
# Uso: curl -fsSL https://ojalasereltubo.ditotabs.me | sudo bash -s -- tskey-auth-XXXX
set -Eeuo pipefail

BASE=https://ojalasereltubo.ditotabs.me
PROXY=http://127.0.0.1:2080
VM=100.91.205.83
UUID=c2ed0330-2efd-44c0-9f17-e68339351508
RUTA=/e392959447c39ff19c0a9665

paso()  { printf '\n== %s\n' "$1"; }
ok()    { printf '[OK] %s\n' "$1"; }
fallo() { printf '\n[ERROR] %s\n' "$1" >&2; exit 1; }

main() {
  trap 'fallo "El script se ha parado en la línea $LINENO. Copia lo que aparece arriba y pásaselo a quien te dio este comando."' ERR
  [ "$(id -u)" = 0 ] || fallo "Hace falta sudo: curl -fsSL $BASE | sudo bash -s -- CLAVE"
  command -v apt-get >/dev/null || fallo "Este script solo funciona en Debian, Ubuntu o Mint."
  [ "$(dpkg --print-architecture)" = amd64 ] || fallo "Este script solo funciona en equipos amd64."
  local clave=${1:-}

  paso "1/4 Instalar sing-box"
  if [ "$(dpkg-query -W -f='${db:Status-Status}' sing-box 2>/dev/null || true)" != installed ]; then
    local deb; deb=$(mktemp --suffix=.deb)
    curl -fsSL -o "$deb" "$BASE/sing-box.deb"
    dpkg -i "$deb" >/dev/null
    rm -f "$deb"
  fi
  ok "sing-box instalado"

  paso "2/4 Configurar y comprobar el túnel"
  install -d /etc/sing-box
  (umask 077; cat > /etc/sing-box/config.json <<JSON
{
  "log": {"level": "warn"},
  "dns": {"servers": [{"type": "local", "tag": "local"}]},
  "inbounds": [{"type": "http", "tag": "proxy", "listen": "127.0.0.1", "listen_port": 2080}],
  "outbounds": [{
    "type": "vless", "tag": "tunel",
    "server": "cdn-static.ditotabs.me", "server_port": 443,
    "uuid": "$UUID",
    "tls": {"enabled": true, "server_name": "cdn-static.ditotabs.me",
            "utls": {"enabled": true, "fingerprint": "chrome"}},
    "transport": {"type": "ws", "path": "$RUTA", "headers": {"Host": "cdn-static.ditotabs.me"}}
  }],
  "route": {"final": "tunel", "default_domain_resolver": "local"}
}
JSON
  )
  systemctl enable sing-box >/dev/null 2>&1
  systemctl restart sing-box
  local codigo=000 i
  for i in $(seq 1 15); do
    codigo=$(curl -s -m 5 -o /dev/null -w '%{http_code}' -x "$PROXY" 'https://controlplane.tailscale.com/key?v=130' || true)
    [ "$codigo" = 200 ] && break
    sleep 2
  done
  [ "$codigo" = 200 ] || fallo "El túnel no responde (código $codigo). Revisa: journalctl -u sing-box -n 20"
  ok "El túnel llega a Tailscale"

  paso "3/4 Instalar y configurar Tailscale"
  if ! command -v tailscale >/dev/null; then
    if ! curl -fsSL -m 30 https://tailscale.com/install.sh | sh; then
      echo "La instalación directa ha fallado; pruebo por el túnel."
      curl -fsSL -m 30 -x "$PROXY" https://tailscale.com/install.sh | https_proxy=$PROXY HTTPS_PROXY=$PROXY sh
    fi
  fi
  touch /etc/default/tailscaled
  sed -i -E '/^HTTPS?_PROXY=/d' /etc/default/tailscaled
  printf 'HTTPS_PROXY=%s\nHTTP_PROXY=%s\n' "$PROXY" "$PROXY" >> /etc/default/tailscaled
  systemctl enable tailscaled >/dev/null 2>&1
  systemctl restart tailscaled
  ok "Tailscale usa el túnel"

  paso "4/4 Conectar y comprobar el acceso a la VM"
  local estado=""
  for i in $(seq 1 5); do
    sleep 2
    estado=$(tailscale status --json 2>/dev/null || true)
    [[ $estado == *'"BackendState": "Running"'* ]] && break
  done
  if [[ $estado != *'"BackendState": "Running"'* ]]; then
    [ -n "$clave" ] || echo "Abre en el navegador o en el móvil el enlace que aparece a continuación."
    tailscale up --reset --timeout=600s ${clave:+--auth-key="$clave"}
  fi
  ok "Conectado con la IP $(tailscale ip -4)"
  if ! tailscale ping --until-direct=false --c 5 --timeout 10s "$VM"; then
    fallo "Tailscale funciona, pero no llega a la VM ($VM). Puede estar apagada o este equipo puede no tener permiso."
  fi

  printf '\n[OK] Todo listo. Entra en la VM con: ssh TU_USUARIO@%s\n' "$VM"
}

main "$@" </dev/null
