#!/bin/bash

# 图片资源展示网站 - 部署脚本
# 使用方法: chmod +x deploy.sh && ./deploy.sh

set -e

echo "========================================="
echo "   图片资源展示网站 - 部署脚本"
echo "========================================="

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        echo "macos"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        if [ -f /etc/debian_version ]; then
            echo "debian"
        elif [ -f /etc/redhat-release ]; then
            echo "redhat"
        else
            echo "linux"
        fi
    else
        echo "unknown"
    fi
}

OS=$(detect_os)
echo "检测到操作系统: $OS"

# 检查并安装 Node.js
install_node() {
    if command -v node &> /dev/null; then
        NODE_VERSION=$(node -v)
        echo "Node.js 已安装: $NODE_VERSION"
        
        # 检查版本是否 >= 14
        NODE_MAJOR=$(echo $NODE_VERSION | cut -d'v'2 | cut -d'.' -f1)
        if [ "$NODE_MAJOR" -ge 14 ]; then
            echo "Node.js 版本满足要求"
            return 0
        else
            echo "Node.js 版本过低，需要重新安装"
        fi
    fi
    
    echo "正在安装 Node.js..."
    
    case $OS in
        macos)
            if command -v brew &> /dev/null; then
                brew install node
            else
                echo "请先安装 Homebrew: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
                exit 1
            fi
            ;;
        debian)
            curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
            sudo apt-get install -y nodejs
            ;;
        redhat)
            curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
            sudo yum install -y nodejs
            ;;
        *)
            echo "请手动安装 Node.js: https://nodejs.org/"
            exit 1
            ;;
    esac
    
    echo "Node.js 安装完成: $(node -v)"
}

# 检查并安装 npm 依赖
install_deps() {
    echo ""
    echo "正在安装项目依赖..."
    
    if [ ! -f package.json ]; then
        echo "错误: 找不到 package.json 文件"
        exit 1
    fi
    
    npm install
    
    echo "依赖安装完成"
}

# 初始化数据库
init_db() {
    echo ""
    echo "正在初始化数据库..."
    
    mkdir -p data
    mkdir -p uploads
    
    echo "数据库初始化完成"
}

# 启动服务
start_server() {
    echo ""
    echo "========================================="
    echo "   启动服务器"
    echo "========================================="
    echo ""
    echo "访问地址:"
    echo "  首页:   http://localhost:3000"
    echo "  登录:   http://localhost:3000/login"
    echo "  后台:   http://localhost:3000/admin"
    echo ""
    echo "默认账号: admin / admin123"
    echo ""
    echo "按 Ctrl+C 停止服务器"
    echo "========================================="
    echo ""
    
    node server.js
}

# 主流程
echo ""
install_node
install_deps
init_db
start_server
