#!/bin/bash
# 自动化部署脚本
# 功能：更新mkdocs.yml -> Git提交推送 -> 服务器拉取并重启

# 配置参数
COMMIT_MESSAGE="${1:-更新文档}"
SERVER_USER="${2:-}"
SERVER_HOST="${3:-}"
SERVER_PATH="${4:-~/devops/mkdocs}"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 输出函数
info() {
    echo -e "${CYAN}$1${NC}"
}

success() {
    echo -e "${GREEN}✓ $1${NC}"
}

error() {
    echo -e "${RED}✗ $1${NC}"
}

warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

# 错误处理
set -e
trap 'error "脚本执行失败，退出码: $?"' ERR

# 步骤1: 更新mkdocs.yml
info "========================================="
info "步骤1: 更新mkdocs.yml"
info "========================================="

if python3 ./add_docs_to_mkdocs.py; then
    success "mkdocs.yml更新成功"
else
    error "更新mkdocs.yml失败"
    exit 1
fi

# 检查是否有变更
info ""
info "检查Git状态..."
if [ -z "$(git status --porcelain)" ]; then
    info "没有文件变更，跳过Git操作"
    exit 0
fi

info "发现以下变更:"
git status --short

# 步骤2: Git操作
info ""
info "========================================="
info "步骤2: Git提交和推送"
info "========================================="

# 添加所有变更
info "添加文件到Git..."
git add .
success "文件已添加到暂存区"

# 提交
info "提交变更..."
git commit -m "$COMMIT_MESSAGE"
success "变更已提交"

# 推送
info "推送到远程仓库..."
git push origin master
success "代码已推送到远程仓库"

# 步骤3: 服务器操作
if [ -n "$SERVER_USER" ] && [ -n "$SERVER_HOST" ]; then
    info ""
    info "========================================="
    info "步骤3: 服务器拉取代码并重启服务"
    info "========================================="
    
    info "连接到服务器: ${SERVER_USER}@${SERVER_HOST}"
    info "执行命令: cd $SERVER_PATH && git pull origin master && docker-compose restart"
    
    if ssh "${SERVER_USER}@${SERVER_HOST}" "cd $SERVER_PATH && git pull origin master && docker-compose restart"; then
        success "服务器代码已更新，服务已重启"
    else
        error "服务器操作失败"
        warning "提示: 请确保已配置SSH密钥，或手动执行服务器命令"
        exit 1
    fi
else
    info ""
    info "========================================="
    info "步骤3: 服务器操作（跳过）"
    info "========================================="
    info "未配置服务器信息，跳过服务器操作"
    info ""
    info "使用方法:"
    info "  ./deploy.sh [提交信息] [服务器用户] [服务器地址] [服务器路径]"
    info ""
    info "示例:"
    info "  ./deploy.sh '更新文档' user example.com ~/devops/mkdocs"
    info ""
    info "或手动执行:"
    info "  ssh user@host 'cd ~/devops/mkdocs && git pull origin master && docker-compose restart'"
fi

info ""
info "========================================="
success "部署完成！"
info "========================================="
