#!/bin/bash
# ===================================================================
# TK Factory Services - 배포 스크립트
# ===================================================================
# 사용법: ./scripts/deploy.sh [--build] [--restart service_name]
# ===================================================================

set -e
cd "$(dirname "$0")/.."

echo "=== TK Factory Services Deploy ==="
echo ""

# .env 파일 확인
if [ ! -f .env ]; then
  echo "ERROR: .env file not found!"
  echo "Run: cp .env.example .env && vi .env"
  exit 1
fi

source .env

case "${1:-}" in
  --build)
    echo "[1/3] Building all services..."
    docker compose build --parallel

    echo "[2/3] Starting services..."
    docker compose up -d

    echo "[3/3] Checking health..."
    sleep 10
    ./scripts/health-check.sh
    ;;

  --restart)
    SERVICE="${2:?Service name required}"
    echo "Restarting $SERVICE..."
    docker compose restart "$SERVICE"
    sleep 5
    docker compose ps "$SERVICE"
    ;;

  --stop)
    echo "Stopping all services..."
    docker compose down
    echo "All services stopped."
    ;;

  --logs)
    SERVICE="${2:-}"
    if [ -n "$SERVICE" ]; then
      docker compose logs -f --tail=100 "$SERVICE"
    else
      docker compose logs -f --tail=50
    fi
    ;;

  --status)
    docker compose ps
    echo ""
    echo "=== Resource Usage ==="
    docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" \
      $(docker compose ps -q 2>/dev/null) 2>/dev/null || echo "No containers running"
    ;;

  *)
    echo "Usage:"
    echo "  ./scripts/deploy.sh --build     # Build and start all services"
    echo "  ./scripts/deploy.sh --restart SERVICE  # Restart a specific service"
    echo "  ./scripts/deploy.sh --stop      # Stop all services"
    echo "  ./scripts/deploy.sh --logs [SERVICE]   # View logs"
    echo "  ./scripts/deploy.sh --status    # Show status and resource usage"
    ;;
esac
