#!/usr/bin/env bash
# 服务器侧部署脚本：构建镜像并滚动更新服务
# 由 Gitea Actions workflow 在 /opt/agentkit/repo 目录下调用
# Usage: bash scripts/deploy.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.deploy.yaml}"
DEPLOY_DIR="${DEPLOY_DIR:-/opt/agentkit}"

cd "$PROJECT_ROOT"

if [ ! -f "$COMPOSE_FILE" ]; then
    echo "❌ 未找到 $COMPOSE_FILE"
    exit 1
fi

if [ ! -f ".env" ]; then
    echo "❌ 未找到 .env 文件，请先通过 Gitea Secrets 生成"
    exit 1
fi

echo "==> 部署目录: $PROJECT_ROOT"
echo "==> Compose 文件: $COMPOSE_FILE"
echo "==> 开始构建镜像..."
docker compose -f "$COMPOSE_FILE" build --pull

echo "==> 滚动重启服务（保留数据卷）..."
docker compose -f "$COMPOSE_FILE" up -d --remove-orphans

echo "==> 当前服务状态:"
docker compose -f "$COMPOSE_FILE" ps

echo "==> 部署完成 ✅"
