#!/bin/bash

# KT财务系统部署脚本
# 使用方法: ./deploy.sh

set -e

SERVER_IP="172.16.74.149"
SERVER_USER="atai"
SERVER_PASS="wengewudi666808"
DEPLOY_PATH="/home/atai/kt-financial-system"
REPO_URL="https://gitea.ktyun.cc/chenjiangjiang/kt-financial-system.git"

echo "=== KT财务系统自动部署 ==="
echo "目标服务器: $SERVER_IP"
echo "部署路径: $DEPLOY_PATH"
echo ""

# 使用sshpass进行SSH连接（如果没有安装sshpass，会提示安装）
if ! command -v sshpass &> /dev/null; then
    echo "⚠️  sshpass 未安装"
    echo "MacOS安装: brew install hudochenkov/sshpass/sshpass"
    echo "Linux安装: sudo apt-get install sshpass"
    exit 1
fi

echo "📦 开始部署..."

sshpass -p "$SERVER_PASS" ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP << 'ENDSSH'
set -e

# 切换到部署目录
cd /home/atai

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "❌ Docker未安装，正在安装..."
    curl -fsSL https://get.docker.com | sh
    sudo usermod -aG docker $USER
    echo "✅ Docker安装完成"
fi

# 检查docker-compose是否安装
if ! command -v docker-compose &> /dev/null; then
    echo "❌ docker-compose未安装，正在安装..."
    sudo curl -L "https://github.com/docker/compose/releases/download/v2.23.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
    echo "✅ docker-compose安装完成"
fi

# 克隆或更新代码
if [ ! -d "kt-financial-system" ]; then
    echo "📥 克隆代码仓库..."
    git clone https://gitea.ktyun.cc/chenjiangjiang/kt-financial-system.git
else
    echo "📥 更新代码..."
    cd kt-financial-system
    git pull origin main
    cd ..
fi

cd kt-financial-system

# 停止旧容器
echo "🛑 停止旧容器..."
sudo docker-compose down || true

# 构建并启动新容器
echo "🚀 构建并启动新容器..."
sudo docker-compose up -d --build

# 清理旧镜像
echo "🧹 清理旧镜像..."
sudo docker image prune -f

# 显示容器状态
echo ""
echo "✅ 部署完成！"
echo ""
echo "📊 容器状态:"
sudo docker-compose ps

echo ""
echo "📝 查看日志:"
echo "docker-compose logs -f"
ENDSSH

echo ""
echo "🎉 部署成功！"
echo "🌐 访问地址: http://$SERVER_IP:8080"
echo ""
echo "📝 常用命令:"
echo "  查看日志: ssh $SERVER_USER@$SERVER_IP 'cd $DEPLOY_PATH && docker-compose logs -f'"
echo "  重启服务: ssh $SERVER_USER@$SERVER_IP 'cd $DEPLOY_PATH && docker-compose restart'"
echo "  停止服务: ssh $SERVER_USER@$SERVER_IP 'cd $DEPLOY_PATH && docker-compose down'"
