#!/bin/bash
set -e

# =============================================
# SESE 安装脚本
# =============================================

APP_NAME="SESE"
APP_PATH="/opt/$APP_NAME"
SERVICE_FILE="/etc/systemd/system/$APP_NAME.service"
LOG_PATH="/var/log/$APP_NAME"

SKIP_FRONTEND=false

# 解析参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-frontend|-s)
            SKIP_FRONTEND=true
            shift
            ;;
        --help|-h)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  --skip-frontend, -s   跳过前端编译"
            echo "  --help, -h            显示帮助"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            echo "使用 $0 --help 查看帮助"
            exit 1
            ;;
    esac
done

# 检测是否在工程目录内
if [ -d ".git" ] && [ -f "main.go" ]; then
    echo "==> 检测到工程目录，更新代码..."
    PROJECT_DIR="$(pwd)"
    git pull origin master
    git submodule update --init --recursive
else
    echo "==> 拉取工程代码..."
    cd /opt
    if [ -d "$APP_NAME" ]; then
        echo "工程已存在，更新代码..."
        cd "$APP_NAME"
        PROJECT_DIR="$(pwd)"
        git pull origin master
        git submodule update --init --recursive
    else
        git clone https://git.lmve.net/kevin/sese-engine-go.git "$APP_NAME"
        cd "$APP_NAME"
        PROJECT_DIR="$(pwd)"
        git submodule update --init --recursive
    fi
fi

echo "==> 检查并停止旧版本..."
if systemctl is-active --quiet "$APP_NAME" 2>/dev/null; then
    echo "停止旧服务..."
    systemctl stop "$APP_NAME"
    systemctl disable "$APP_NAME" 2>/dev/null || true
fi

# 清理旧进程
pkill -f "$APP_PATH/$APP_NAME" 2>/dev/null || true

echo "==> 安装依赖..."

# 安装必要工具
if command -v apt-get &> /dev/null; then
    apt-get update
    apt-get install -y git nodejs npm golang-go make
elif command -v yum &> /dev/null; then
    yum install -y git nodejs npm golang make
elif command -v pacman &> /dev/null; then
    pacman -Sy --noconfirm git nodejs npm go make
fi

echo "==> 创建目录..."
mkdir -p "$APP_PATH"
mkdir -p "$(dirname "$LOG_PATH")"
mkdir -p "$APP_PATH/savedata"

# 编译前端
if [ "$SKIP_FRONTEND" = false ]; then
    echo "==> 编译前端..."
    cd "$PROJECT_DIR/sese-engine-ui"
    npm install
    npm run build
else
    echo "==> 跳过前端编译 (--skip-frontend)"
fi

echo "==> 编译后端..."
cd "$PROJECT_DIR"
go mod download
go build -o "$APP_NAME" .

echo "==> 部署到 $APP_PATH..."
mkdir -p "$APP_PATH"
cp "$PROJECT_DIR/$APP_NAME" "$APP_PATH/"
cp -r "$PROJECT_DIR/dist" "$APP_PATH/"
cp -r "$PROJECT_DIR/dict" "$APP_PATH/"

echo "==> 配置用户..."
if id -u www &> /dev/null; then
    echo "用户 www 已存在，跳过创建"
else
    echo "创建用户 www..."
    useradd -r -s /usr/sbin/nologin -d /var/www -M www
fi

echo "==> 配置权限..."
chown -R www:www "$APP_PATH"
chown -R www:www "$LOG_PATH"
chmod +x "$APP_PATH/$APP_NAME"

echo "==> 创建 systemd 服务..."
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=SESE Engine - Web Crawler & Search Engine
Documentation=https://git.lmve.net/kevin/sese-engine-go.git
After=network.target

[Service]
Type=simple
User=www
Group=www
WorkingDirectory=$APP_PATH
ExecStart=$APP_PATH/$APP_NAME
Restart=always
RestartSec=5
StandardOutput=append:$LOG_PATH/stdout.log
StandardError=append:$LOG_PATH/stderr.log

# 安全加固
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$APP_PATH $LOG_PATH

[Install]
WantedBy=multi-user.target
EOF

echo "==> 重新加载 systemd 并启动服务..."
systemctl daemon-reload
systemctl enable "$APP_NAME"
systemctl restart "$APP_NAME"

echo ""
echo "==> 安装完成！"
echo "   服务状态: systemctl status $APP_NAME"
echo "   日志查看: journalctl -u $APP_NAME -f"
echo "   应用日志: tail -f $LOG_PATH/stdout.log"
