#!/bin/bash

#===============================================================================
# 前端生产环境构建并部署脚本
#
# 使用方法:
#   ./deploy-frontend.sh user@host
#   或
#   export REMOTE_USER=root
#   export REMOTE_HOST=8.148.151.56
#   ./deploy-frontend.sh
#===============================================================================

set -e

# 配置
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRONTEND_DIR="$SCRIPT_DIR/lesingle-edu-reading-platform-frontend"
REMOTE_DIR="/www/wwwroot/reading.ycapp.cn"

# SSH 配置（可通过环境变量覆盖）
REMOTE_USER="${REMOTE_USER:-root}"
REMOTE_HOST="${REMOTE_HOST:-}"
REMOTE_PORT="${REMOTE_PORT:-22}"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_step() { echo -e "${BLUE}[STEP]${NC} $1"; }

# 检查参数
if [ -n "$1" ]; then
    if [[ "$1" == *"@"* ]]; then
        REMOTE_USER=$(echo "$1" | cut -d'@' -f1)
        REMOTE_HOST=$(echo "$1" | cut -d'@' -f2)
    fi
fi

if [ -z "$REMOTE_HOST" ]; then
    log_error "请提供远程主机：$0 user@host 或设置 REMOTE_HOST 环境变量"
    exit 1
fi

echo ""
echo "=============================================="
echo "  前端部署到宝塔"
echo "=============================================="
echo ""
echo "  远程主机：$REMOTE_USER@$REMOTE_HOST"
echo "  部署目录：$REMOTE_DIR"
echo ""

cd "$FRONTEND_DIR"

# 步骤 1: 检查 Node.js
log_step "检查环境..."
if ! command -v node &> /dev/null; then
    log_error "未找到 Node.js"
    exit 1
fi
node_version=$(node -v)
npm_version=$(npm -v)
log_info "Node.js: $node_version, npm: $npm_version"

# 步骤 2: 安装依赖
log_step "安装依赖..."
if [ ! -d "node_modules" ]; then
    npm install
else
    log_info "node_modules 已存在，跳过依赖安装"
fi

# 步骤 3: 构建
log_step "构建前端..."
npm run build

if [ ! -d "dist" ]; then
    log_error "构建失败，未找到 dist 目录"
    exit 1
fi
log_info "构建成功"

# 步骤 4: 上传到服务器
log_step "上传到远程服务器..."

# 创建远程目录
ssh -o StrictHostKeyChecking=no -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" \
    "mkdir -p $REMOTE_DIR"

# 上传文件
scp -o StrictHostKeyChecking=no -r -P "$REMOTE_PORT" \
    dist/ \
    "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"

log_info "上传完成"

# 步骤 5: 设置权限
log_step "设置文件权限..."
ssh -o StrictHostKeyChecking=no -p "$REMOTE_PORT" "$REMOTE_USER@$REMOTE_HOST" << 'ENDSSH'
    chown -R www:www /www/wwwroot/reading.ycapp.cn
    chmod -R 755 /www/wwwroot/reading.ycapp.cn
ENDSSH

echo ""
echo "=============================================="
echo "  前端部署完成！"
echo "=============================================="
echo ""
echo "  访问地址：http://${REMOTE_HOST}"
echo ""
echo "  下一步：在宝塔面板配置 Nginx 反向代理"
echo "  /api -> http://localhost:8480"
echo ""
