# Gitea Actions Workflow - vexplor 이미지 빌드 & Harbor Push
#
# 동작 방식:
#   1. main 브랜치에 push 시 자동 실행
#   2. Docker 이미지 빌드 (Backend, Frontend)
#   3. Harbor 레지스트리에 Push
#   4. 공장 서버의 Watchtower가 새 이미지 감지 후 자동 업데이트
#
# 필수 Secrets (Repository Settings > Secrets):
#   - HARBOR_USERNAME: Harbor 사용자명
#   - HARBOR_PASSWORD: Harbor 비밀번호

name: Build and Push Images

on:
  push:
    branches:
      - main
      - master
    paths:
      - "backend-node/**"
      - "frontend/**"
      - "docker/**"
      - ".gitea/workflows/deploy.yml"
    paths-ignore:
      - "**.md"
      - "deploy/**"
      - "k8s/**"
  workflow_dispatch:  # 수동 실행도 가능

env:
  GITEA_DOMAIN: g.wace.me
  HARBOR_REGISTRY: localhost:5001
  HARBOR_REGISTRY_EXTERNAL: harbor.wace.me
  HARBOR_PROJECT: speefox_vexplor

  # Frontend 빌드 환경 변수
  NEXT_PUBLIC_API_URL: "https://api.vexplor.com/api"
  NEXT_PUBLIC_ENV: "production"

  # Frontend 설정
  FRONTEND_IMAGE_NAME: vexplor-frontend
  FRONTEND_BUILD_CONTEXT: frontend
  FRONTEND_DOCKERFILE_PATH: docker/deploy/frontend.Dockerfile

  # Backend 설정
  BACKEND_IMAGE_NAME: vexplor-backend
  BACKEND_BUILD_CONTEXT: backend-node
  BACKEND_DOCKERFILE_PATH: docker/deploy/backend.Dockerfile

jobs:
  build-and-push:
    runs-on: ubuntu-24.04

    steps:
      # 작업 디렉토리 정리
      - name: Clean workspace
        run: |
          echo "작업 디렉토리 정리..."
          cd /workspace
          rm -rf source
          mkdir -p source
          echo "정리 완료"

      # 필수 도구 설치
      - name: Install required tools
        run: |
          echo "필수 도구 설치 중..."
          apt-get update -qq
          apt-get install -y git curl ca-certificates gnupg

          # Docker 클라이언트 설치
          install -m 0755 -d /etc/apt/keyrings
          curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
          chmod a+r /etc/apt/keyrings/docker.asc

          echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
            $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

          apt-get update -qq
          apt-get install -y docker-ce-cli

          echo "설치 완료:"
          git --version
          docker --version

          export DOCKER_HOST=unix:///var/run/docker.sock
          docker version || echo "소켓 연결 대기 중..."

      # 저장소 체크아웃
      - name: Checkout code
        run: |
          echo "저장소 체크아웃..."
          cd /workspace/source

          git clone --depth 1 --branch ${GITHUB_REF_NAME} \
            https://oauth2:${{ github.token }}@${GITEA_DOMAIN}/${GITHUB_REPOSITORY}.git .

          echo "체크아웃 완료"
          git log -1 --oneline

      # 빌드 환경 설정
      - name: Set up build environment
        run: |
          IMAGE_TAG="v$(date +%Y%m%d-%H%M%S)-${GITHUB_SHA::7}"
          echo "IMAGE_TAG=${IMAGE_TAG}" >> $GITHUB_ENV

          # Frontend 이미지
          echo "FRONTEND_FULL_IMAGE=${HARBOR_REGISTRY}/${HARBOR_PROJECT}/${FRONTEND_IMAGE_NAME}" >> $GITHUB_ENV

          # Backend 이미지
          echo "BACKEND_FULL_IMAGE=${HARBOR_REGISTRY}/${HARBOR_PROJECT}/${BACKEND_IMAGE_NAME}" >> $GITHUB_ENV

          echo "=========================================="
          echo "빌드 태그: ${IMAGE_TAG}"
          echo "=========================================="

      # Harbor 로그인
      - name: Login to Harbor
        env:
          HARBOR_USER: ${{ secrets.HARBOR_USERNAME }}
          HARBOR_PASS: ${{ secrets.HARBOR_PASSWORD }}
        run: |
          echo "Harbor 로그인..."
          export DOCKER_HOST=unix:///var/run/docker.sock
          echo "${HARBOR_PASS}" | docker login ${HARBOR_REGISTRY} \
            --username ${HARBOR_USER} \
            --password-stdin
          echo "Harbor 로그인 완료"

      # Backend 빌드 및 푸시
      - name: Build and Push Backend image
        run: |
          echo "=========================================="
          echo "Backend 이미지 빌드 시작..."
          echo "=========================================="
          export DOCKER_HOST=unix:///var/run/docker.sock
          cd /workspace/source

          docker build \
            -t ${BACKEND_FULL_IMAGE}:${IMAGE_TAG} \
            -t ${BACKEND_FULL_IMAGE}:latest \
            -f ${BACKEND_DOCKERFILE_PATH} \
            ${BACKEND_BUILD_CONTEXT}

          echo "Backend 이미지 푸시..."
          docker push ${BACKEND_FULL_IMAGE}:${IMAGE_TAG}
          docker push ${BACKEND_FULL_IMAGE}:latest
          
          echo "=========================================="
          echo "Backend 푸시 완료!"
          echo "  - ${BACKEND_FULL_IMAGE}:${IMAGE_TAG}"
          echo "  - ${BACKEND_FULL_IMAGE}:latest"
          echo "=========================================="

      # Frontend 빌드 및 푸시
      - name: Build and Push Frontend image
        run: |
          echo "=========================================="
          echo "Frontend 이미지 빌드 시작..."
          echo "=========================================="
          export DOCKER_HOST=unix:///var/run/docker.sock
          cd /workspace/source

          echo "빌드 환경 변수:"
          echo "  NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}"
          echo "  NEXT_PUBLIC_ENV=${NEXT_PUBLIC_ENV}"

          docker build \
            -t ${FRONTEND_FULL_IMAGE}:${IMAGE_TAG} \
            -t ${FRONTEND_FULL_IMAGE}:latest \
            -f ${FRONTEND_DOCKERFILE_PATH} \
            --build-arg NEXT_PUBLIC_API_URL="${NEXT_PUBLIC_API_URL}" \
            ${FRONTEND_BUILD_CONTEXT}

          echo "Frontend 이미지 푸시..."
          docker push ${FRONTEND_FULL_IMAGE}:${IMAGE_TAG}
          docker push ${FRONTEND_FULL_IMAGE}:latest
          
          echo "=========================================="
          echo "Frontend 푸시 완료!"
          echo "  - ${FRONTEND_FULL_IMAGE}:${IMAGE_TAG}"
          echo "  - ${FRONTEND_FULL_IMAGE}:latest"
          echo "=========================================="

      # 빌드 완료 요약
      - name: Build summary
        if: success()
        run: |
          echo ""
          echo "=========================================="
          echo "  이미지 빌드 & Push 완료!"
          echo "=========================================="
          echo ""
          echo "빌드 버전: ${IMAGE_TAG}"
          echo ""
          echo "푸시된 이미지:"
          echo "  - Backend:  ${HARBOR_REGISTRY_EXTERNAL}/${HARBOR_PROJECT}/${BACKEND_IMAGE_NAME}:latest"
          echo "  - Frontend: ${HARBOR_REGISTRY_EXTERNAL}/${HARBOR_PROJECT}/${FRONTEND_IMAGE_NAME}:latest"
          echo ""
          echo "다음 단계:"
          echo "  - 공장 서버의 Watchtower가 자동으로 새 이미지를 감지합니다"
          echo "  - 또는 수동 업데이트: docker compose pull && docker compose up -d"
          echo ""
          echo "=========================================="

      # Harbor 로그아웃
      - name: Logout from Harbor
        if: always()
        run: |
          export DOCKER_HOST=unix:///var/run/docker.sock
          docker logout ${HARBOR_REGISTRY} || true
