#!/bin/bash
# 服务器本地部署控制脚本
# 用法: ./deploy-control.sh [staging|production] [deploy|status|logs|restart]

set -eu

ENV="${1:-staging}"
ACTION="${2:-deploy}"

if [ "$ENV" = "staging" ]; then
    WORKSPACE="/var/lib/xiaoxia-saas-staging"
    COMPOSE_DIR="$WORKSPACE/repo/infra/docker"
    DEPLOY_SCRIPT="$WORKSPACE/repo/infra/docker/deploy-staging.sh"
elif [ "$ENV" = "production" ]; then
    WORKSPACE="/var/lib/xiaoxia-saas-production"
    COMPOSE_DIR="$WORKSPACE/repo/infra/docker"
    DEPLOY_SCRIPT="$WORKSPACE/repo/infra/docker/deploy-production.sh"
else
    echo "Usage: $0 [staging|production] [deploy|status|logs|restart]"
    exit 1
fi

cd "$COMPOSE_DIR"
if [ "$ENV" = "production" ]; then
    export COMPOSE_PROJECT_NAME=xiaoxia-production-app
    COMPOSE_ENV_FILE="$WORKSPACE/.env"
else
    COMPOSE_ENV_FILE="$WORKSPACE/.env"
fi

case "$ACTION" in
    deploy)
        echo "开始部署 $ENV 环境..."
        chmod +x "$DEPLOY_SCRIPT"
        if [ "$ENV" = "production" ]; then
            HOST_PREFIX="" "$DEPLOY_SCRIPT" 2>&1 | tee "$WORKSPACE/deploy.log"
        else
            "$DEPLOY_SCRIPT" 2>&1 | tee "$WORKSPACE/deploy.log"
        fi
        ;;
    status)
        docker compose --env-file "$COMPOSE_ENV_FILE" ps
        ;;
    logs)
        SERVICE="${3:-api}"
        docker compose --env-file "$COMPOSE_ENV_FILE" logs -f --tail=100 "$SERVICE"
        ;;
    restart)
        SERVICE="${3:-all}"
        if [ "$SERVICE" = "all" ]; then
            docker compose --env-file "$COMPOSE_ENV_FILE" restart
        else
            docker compose --env-file "$COMPOSE_ENV_FILE" restart "$SERVICE"
        fi
        ;;
    *)
        echo "未知操作: $ACTION"
        echo "支持: deploy, status, logs, restart"
        exit 1
        ;;
esac
