#!/usr/bin/env bash
# @desc: 检查 HTTPS 证书：到期时间/剩余天数/签发者/证书链，快过期会标出来
# @usage: wcl tls <域名>[:端口]
#   wcl tls md.melulu.top
#   wcl tls example.com:8443
#
# 零依赖（python3 即可），不装 openssl 也能用。默认 30 天内到期标红。

TARGET="${1:-}"
if [ -z "$TARGET" ]; then
  printf '用法: wcl tls <域名>[:端口]\n'
  printf '  wcl tls md.melulu.top\n'
  printf '  wcl tls example.com:8443\n'
  exit 2
fi

case "$TARGET" in
  *://*)
    printf '域名不要带协议前缀，直接写域名[:端口]\n' >&2
    exit 2 ;;
esac

HOST="${TARGET%%:*}"
PORT=443
case "$TARGET" in
  *:*) PORT="${TARGET##*:}" ;;
esac
case "$PORT" in
  ''|*[!0-9]*) printf '端口不合法: %s\n' "$PORT" >&2; exit 2 ;;
esac

have() { command -v "$1" >/dev/null 2>&1; }

if have python3; then
  python3 - "$HOST" "$PORT" <<'PYEOF'
import socket, ssl, sys, datetime

host, port = sys.argv[1], int(sys.argv[2])

print("=" * 58)
print(" 证书检查: %s:%d" % (host, port))
print("=" * 58)
print()

ctx = ssl.create_default_context()
try:
    with socket.create_connection((host, port), timeout=10) as raw:
        with ctx.wrap_socket(raw, server_hostname=host) as ss:
            cert = ss.getpeercert()
            ver = ss.version()
            cipher = ss.cipher()
except socket.timeout:
    print("连接超时（10 秒）：端口不通或被防火墙挡了")
    sys.exit(1)
except ssl.SSLCertVerificationError as e:
    print("证书校验失败 —— 这一项本身就是要修的问题")
    print("  原因: %s" % e.verify_message)
    print("  常见情况: 证书过期 / 域名不匹配 / 自签证书 / 中间证书缺失")
    sys.exit(2)
except ssl.SSLError as e:
    print("TLS 握手失败: %s" % e)
    print("  该端口可能不是 HTTPS，或者不支持客户端要求的 TLS 版本")
    sys.exit(1)
except Exception as e:
    print("连接失败: %s" % e)
    sys.exit(1)

def name_of(field):
    return ", ".join("%s=%s" % (k, v) for pair in field for k, v in pair) if field else "-"

not_before = datetime.datetime.strptime(cert["notBefore"], "%b %d %H:%M:%S %Y %Z")
not_after = datetime.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
# 用 timezone-aware 取当前时间再转 naive UTC：utcnow() 已废弃，
# 3.12+ 会打 DeprecationWarning
now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
left = (not_after - now).days

print("主体      : %s" % name_of(cert.get("subject")))
print("签发者    : %s" % name_of(cert.get("issuer")))
print("生效时间  : %s UTC" % not_before.strftime("%Y-%m-%d %H:%M"))
print("到期时间  : %s UTC" % not_after.strftime("%Y-%m-%d %H:%M"))
print()
print("剩余天数  : %d 天%s" % (left, "   <<< 快到期了" if left <= 30 else ""))
print("TLS 版本  : %s" % ver)
print("加密套件  : %s" % (cipher[0] if cipher else "-"))
print()

sans = [v for k, v in cert.get("subjectAltName", ()) if k == "DNS"]
if sans:
    print("覆盖域名  : %s" % ", ".join(sans[:8]) + (" ..." if len(sans) > 8 else ""))
    if host not in sans and not any(s.startswith("*.") and host.endswith(s[1:]) for s in sans):
        print("           注意: 当前访问的 %s 不在上面列表中（可能靠泛域名匹配）" % host)
print()
print("证书链    : 校验通过（系统 CA 认可）")
print()
if left <= 0:
    print("结论: 已过期，HTTPS 会直接报错")
    sys.exit(3)
elif left <= 14:
    print("结论: %d 天内过期，尽快续期" % left)
elif left <= 30:
    print("结论: 一个月内到期，排个续期计划")
else:
    print("结论: 正常")
PYEOF
  exit $?
fi

# ---- 没有 python3: 用 openssl ----
if have openssl; then
  printf '（没有 python3，使用 openssl）\n\n'
  OUT="$(echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" 2>/dev/null)"
  if [ -z "$OUT" ]; then
    printf 'openssl 连不上 %s:%s\n' "$HOST" "$PORT" >&2
    printf '  可能: 端口不通 / 不是 HTTPS / 需要 SNI 以外的配置\n' >&2
    exit 1
  fi
  printf '%s\n' "$OUT" | grep -E 'subject=|issuer=|notBefore=|notAfter=|Protocol|Cipher' | sed 's/^[[:space:]]*//'
  END="$(printf '%s\n' "$OUT" | sed -n 's/^notAfter=//p' | head -1)"
  if [ -n "$END" ]; then
    printf '\n到期时间: %s\n' "$END"
    printf '剩余天数: '
    if date -d "$END" +%s >/dev/null 2>&1; then
      printf '%s 天\n' "$(( ($(date -d "$END" +%s) - $(date +%s)) / 86400 ))"
    else
      printf '(这个系统的 date 不支持 -d，跳过计算)\n'
    fi
  fi
  exit 0
fi

printf 'tls: 需要 python3 或 openssl\n' >&2
printf '    Debian/Ubuntu   sudo apt install -y python3\n' >&2
printf '    OpenWrt         opkg update && opkg install python3-light\n' >&2
printf '    Alpine          apk add python3\n' >&2
printf '    CentOS/RHEL     sudo dnf install -y python3\n' >&2
exit 1