#!/bin/bash
# SafeSight Control 一键安装/升级脚本
# 用法: sudo bash install.sh
set -e

if [ "$EUID" -ne 0 ]; then
    echo "请用 sudo 运行"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="${1:-/opt/safesightd}"
ARCH=$(uname -m)
UPGRADE=false

if [ -f "$INSTALL_DIR/bin/safesightd" ]; then
    UPGRADE=true
    echo "========== SafeSight Control 升级 =========="
    echo "检测到已有安装，将保留数据库和配置文件"
    systemctl stop safesightd 2>/dev/null || true
else
    echo "========== SafeSight Control 安装 =========="
fi
echo "安装目录: $INSTALL_DIR"

# 选二进制
if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
    BIN="safesightd-linux-arm64"
elif [ "$ARCH" = "x86_64" ]; then
    BIN="safesightd-linux-amd64"
else
    echo "不支持的架构: $ARCH"
    exit 1
fi

# 创建目录
mkdir -p "$INSTALL_DIR"/{bin,config,data,configs,tools,scripts,models/standard_models,resources/standard_resources/face_gallery}

# 复制二进制（始终更新）
cp "$SCRIPT_DIR/$BIN" "$INSTALL_DIR/bin/safesightd"
chmod +x "$INSTALL_DIR/bin/safesightd"

# 配置文件：仅在全新安装时创建，升级保留
if [ "$UPGRADE" = false ] && [ -f "$SCRIPT_DIR/safesightd.json.example" ]; then
    cp "$SCRIPT_DIR/safesightd.json.example" "$INSTALL_DIR/config/safesightd.json"
    echo "  ✓ 配置已创建（请修改 agent_token）"
else
    echo "  ✓ 配置文件保留"
fi

# 种子数据、工具、脚本（始终更新）
[ -d "$SCRIPT_DIR/configs" ] && cp -r "$SCRIPT_DIR/configs"/* "$INSTALL_DIR/configs/" 2>/dev/null && echo "  ✓ 种子数据已更新"
[ -d "$SCRIPT_DIR/tools" ] && cp -r "$SCRIPT_DIR/tools"/* "$INSTALL_DIR/tools/" 2>/dev/null && echo "  ✓ 构建工具已更新"
[ -d "$SCRIPT_DIR/scripts" ] && cp -r "$SCRIPT_DIR/scripts"/* "$INSTALL_DIR/scripts/" 2>/dev/null && echo "  ✓ 脚本已更新"
[ -d "$SCRIPT_DIR/models" ] && cp -r "$SCRIPT_DIR/models"/* "$INSTALL_DIR/models/" 2>/dev/null && echo "  ✓ 标准模型已更新"
[ -d "$SCRIPT_DIR/deps" ] && rm -rf "$INSTALL_DIR/deps/" && cp -r "$SCRIPT_DIR/deps" "$INSTALL_DIR/" 2>/dev/null && echo "  ✓ 依赖包已更新"

# 安装 Python 依赖（全局，root 可访问）
if [ -d "$INSTALL_DIR/deps" ] && ls "$INSTALL_DIR/deps"/*.whl >/dev/null 2>&1; then
    # 先确保 pip3 可用（离线安装）
    if ! command -v pip3 &>/dev/null; then
        if [ -f "$INSTALL_DIR/deps/get-pip.py" ]; then
            PIP_ROOT_USER_ACTION=ignore python3 "$INSTALL_DIR/deps/get-pip.py" --no-index --find-links="$INSTALL_DIR/deps/" --no-setuptools --no-wheel 2>&1
        fi
    fi
    if pip3 install --force-reinstall --root-user-action=ignore "$INSTALL_DIR"/deps/*.whl 2>&1; then
        echo "  ✓ Python 依赖已安装"
    else
        echo "  ⚠ Python 依赖安装失败，尝试桥接用户包..."
        # Fallback: let root's Python see the current user's site-packages
        USER_SITE=$(python3 -c "import site; print(site.USER_SITE)" 2>/dev/null)
        if [ -n "$USER_SITE" ] && [ -d "$USER_SITE" ]; then
            SYS_SITE=$(python3 -c "import site; print(site.getsitepackages()[0])" 2>/dev/null)
            echo "$USER_SITE" > "$SYS_SITE/orangepi-local.pth" 2>/dev/null && echo "  ✓ 用户包桥接已创建" || echo "  ⚠ 桥接失败"
        fi
    fi
fi

# 安装/更新服务
cp "$SCRIPT_DIR/safesightd.service" /etc/systemd/system/
systemctl daemon-reload

if [ "$UPGRADE" = true ]; then
    systemctl start safesightd
else
    systemctl enable --now safesightd
fi

echo ""
echo "========== 完成 =========="
systemctl status safesightd --no-pager -l | head -10
echo ""
echo "打开 http://$(hostname -I | awk '{print $1}'):18080"
