#!/usr/bin/env bash
#
# cloudflared-ssh status
# ---------------------------------------------------------------------------
# 查看当前 tunnel 状态与域名（断开重连后仍能找回，无需重跑 setup.sh）。
# ---------------------------------------------------------------------------
set -euo pipefail
TUN_LOG="/tmp/cf-ssh-tunnel.log"
INFO_FILE="/root/.cf-ssh-info"

DOMAIN=$(grep -oE 'https://[a-z0-9.-]+\.trycloudflare\.com' "$TUN_LOG" 2>/dev/null | head -1 || true)

if pgrep -f 'cloudflared tunnel --url ssh://localhost:22' >/dev/null 2>&1; then
  echo "tunnel : 运行中"
else
  echo "tunnel : 未运行（运行 setup.sh 重新开启）"
fi

if [ -n "$DOMAIN" ]; then
  echo "域名   : $DOMAIN"
  echo "连接   : ssh -o ProxyCommand=\"cloudflared access ssh --hostname %h\" root@$DOMAIN"
else
  echo "域名   : (未知，tunnel 未运行或日志已清理)"
fi

if [ -f "$INFO_FILE" ]; then
  echo "----- 保存的连接信息 ($INFO_FILE) -----"
  cat "$INFO_FILE"
fi
