#!/bin/bash
# 前端构建和部署脚本

echo "========== 萌芽短链前端部署 =========="

# 安装依赖
echo "安装依赖..."
npm install

# 构建
echo "构建前端..."
npm run build

# 创建部署目录
echo "创建部署目录..."
mkdir -p /shumengya/www/mengyalinkfly-frontend

# 备份旧文件
if [ -d "/shumengya/www/mengyalinkfly-frontend/index.html" ]; then
  echo "备份旧版本..."
  backup_dir="/shumengya/www/mengyalinkfly-frontend-backup-$(date +%Y%m%d-%H%M%S)"
  mkdir -p "$backup_dir"
  cp -r /shumengya/www/mengyalinkfly-frontend/* "$backup_dir/"
fi

# 部署新文件
echo "部署新文件..."
cp -r dist/* /shumengya/www/mengyalinkfly-frontend/

# 复制nginx配置
echo "更新nginx配置..."
cp ../nginx.conf /etc/nginx/sites-available/mengyalinkfly

# 创建软链接（如果不存在）
if [ ! -L "/etc/nginx/sites-enabled/mengyalinkfly" ]; then
  ln -s /etc/nginx/sites-available/mengyalinkfly /etc/nginx/sites-enabled/
fi

# 测试nginx配置
echo "测试nginx配置..."
nginx -t

# 重启nginx
if [ $? -eq 0 ]; then
  echo "重启nginx..."
  systemctl restart nginx
  echo ""
  echo "========== 部署完成 =========="
  echo "前端地址：http://localhost:8989"
else
  echo "Nginx配置错误，请检查！"
  exit 1
fi
