#!/bin/bash
# ============================================================
# sgClaw 验证报告 — 局域网 HTTP 服务启动脚本
#
# 用法:
#   ./serve.sh              # 默认 8080 端口
#   ./serve.sh 9090         # 指定端口
#
# 局域网访问:
#   同网段机器浏览器打开 http://<本机IP>:<端口>/index.html
# ============================================================

set -e

PORT="${1:-8080}"
DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR"

# 获取本机 IP (兼容银河麒麟 / Ubuntu / CentOS)
get_ip() {
  # 优先取非 127 的第一个 IPv4
  ip -4 addr show 2>/dev/null \
    | grep -oP 'inet \K[\d.]+' \
    | grep -v '127.0.0.1' \
    | head -1
}

LOCAL_IP=$(get_ip)
if [ -z "$LOCAL_IP" ]; then
  # fallback: hostname
  LOCAL_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
fi
if [ -z "$LOCAL_IP" ]; then
  LOCAL_IP="<本机IP>"
fi

echo ""
echo "  ╔══════════════════════════════════════════════════╗"
echo "  ║   sgClaw · AI Agent 验证报告                     ║"
echo "  ╠══════════════════════════════════════════════════╣"
echo "  ║                                                  ║"
echo "  ║   本机访问:   http://localhost:${PORT}/index.html"
echo "  ║   局域网访问: http://${LOCAL_IP}:${PORT}/index.html"
echo "  ║                                                  ║"
echo "  ║   按 Ctrl+C 停止服务                              ║"
echo "  ╚══════════════════════════════════════════════════╝"
echo ""

# 优先使用 Python 3，兼容银河麒麟和各 Linux 发行版
if command -v python3 &>/dev/null; then
  python3 -m http.server "$PORT" --bind 0.0.0.0
elif command -v python &>/dev/null; then
  # Python 2 fallback
  python -m SimpleHTTPServer "$PORT"
else
  echo "[Error] 未找到 Python，请安装 python3 或使用其他 HTTP 服务器"
  echo ""
  echo "  替代方案:"
  echo "    1. sudo apt install python3"
  echo "    2. npx serve -l $PORT      (需要 Node.js)"
  echo "    3. busybox httpd -f -p $PORT  (银河麒麟可能自带)"
  exit 1
fi
