#!/bin/bash
set -euo pipefail

# ================================================
# invyone Kubernetes 배포 스크립트
# 사용법: ./k8s/deploy.sh [build|deploy|all]
# ================================================

REGISTRY="localhost:5000"
PROJECT="invyone"
TAG="${GIT_COMMIT_SHORT:-latest}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() { echo -e "${GREEN}[DEPLOY]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# 프로젝트 루트 디렉토리로 이동
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT"

build_images() {
    log "Docker 이미지 빌드 시작..."

    log "1/2 Backend Spring 빌드..."
    docker build -t "$REGISTRY/$PROJECT/backend-spring:$TAG" \
        -f docker/deploy/backend-spring.Dockerfile \
        backend-spring/

    log "2/2 Frontend 빌드..."
    docker build -t "$REGISTRY/$PROJECT/frontend:$TAG" \
        -f docker/deploy/frontend.Dockerfile \
        frontend/

    log "Docker 이미지 빌드 완료!"
}

push_images() {
    log "Docker Registry로 이미지 Push..."

    docker push "$REGISTRY/$PROJECT/backend-spring:$TAG"
    docker push "$REGISTRY/$PROJECT/frontend:$TAG"

    # latest 태그도 push
    if [ "$TAG" != "latest" ]; then
        docker tag "$REGISTRY/$PROJECT/backend-spring:$TAG" "$REGISTRY/$PROJECT/backend-spring:latest"
        docker tag "$REGISTRY/$PROJECT/frontend:$TAG" "$REGISTRY/$PROJECT/frontend:latest"
        docker push "$REGISTRY/$PROJECT/backend-spring:latest"
        docker push "$REGISTRY/$PROJECT/frontend:latest"
    fi

    log "이미지 Push 완료!"
}

deploy_k8s() {
    log "Kubernetes 배포 시작..."

    # Namespace 생성
    kubectl apply -f k8s/namespace.yaml

    # Secret & ConfigMap (Secret은 이미 존재하면 skip)
    kubectl apply -f k8s/secrets.yaml
    kubectl apply -f k8s/configmap.yaml

    # PVC
    kubectl apply -f k8s/pvc.yaml

    # Deployments & Services
    kubectl apply -f k8s/backend-spring.yaml
    kubectl apply -f k8s/frontend.yaml

    # NetworkPolicy
    kubectl apply -f k8s/networkpolicy.yaml

    # 이미지 태그가 latest가 아니면 이미지 업데이트
    if [ "$TAG" != "latest" ]; then
        kubectl set image deployment/backend-spring \
            backend-spring="$REGISTRY/$PROJECT/backend-spring:$TAG" \
            -n invyone
        kubectl set image deployment/frontend \
            frontend="$REGISTRY/$PROJECT/frontend:$TAG" \
            -n invyone
    fi

    # Rollout 대기
    log "Rollout 대기 중..."
    kubectl rollout status deployment/backend-spring -n invyone --timeout=180s || warn "backend-spring rollout timeout"
    kubectl rollout status deployment/frontend -n invyone --timeout=120s || warn "frontend rollout timeout"

    log "Kubernetes 배포 완료!"
    kubectl get pods -n invyone
}

case "${1:-all}" in
    build)
        build_images
        push_images
        ;;
    deploy)
        deploy_k8s
        ;;
    all)
        build_images
        push_images
        deploy_k8s
        ;;
    *)
        echo "사용법: $0 [build|deploy|all]"
        exit 1
        ;;
esac
