#!/usr/bin/env bash
# BillCare post-receive — Track A (git push main → deploy-billcare.sh)
# 설치: cp scripts/post-receive /Volumes/ADATA/git/BillCare.git/hooks/post-receive && chmod +x ...
set -euo pipefail

GIT_DIR="/Volumes/ADATA/git/BillCare.git"
WORK_TREE="${WORK_TREE:-/Users/aidev/apps/BillCare}"
DEPLOY_SCRIPT="/Volumes/ADATA/git/deploy-billcare.sh"
SUMMARY_SCRIPT="/Volumes/ADATA/git/git-push-summary.sh"
DEPLOY_LOG="/Volumes/ADATA/logs/deploy/billcare-deploy.log"
SUMMARY_DIR="/Volumes/ADATA/logs/deploy/push-summaries"
HOOK_TAG="[billcare-post-receive]"

mkdir -p "$(dirname "$DEPLOY_LOG")" "$SUMMARY_DIR"

echo ""
echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG =============================="
echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG Track A — git push 수신"
echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG =============================="

while read -r OLDREV NEWREV REFNAME; do
  BRANCH_NAME="${REFNAME#refs/heads/}"
  echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG 브랜치: $BRANCH_NAME ($OLDREV → $NEWREV)"

  if [ -x "$SUMMARY_SCRIPT" ]; then
    SUMMARY_FILE="$("$SUMMARY_SCRIPT" "$GIT_DIR" "$OLDREV" "$NEWREV" "$REFNAME" "$SUMMARY_DIR" || true)"
    if [ -n "${SUMMARY_FILE:-}" ] && [ -f "$SUMMARY_FILE" ]; then
      echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG 변경 요약: $SUMMARY_FILE"
      head -20 "$SUMMARY_FILE" | sed "s/^/$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG   /"
    fi
  fi

  if [ "$BRANCH_NAME" = "main" ]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG main → deploy-billcare.sh 실행"
    export SERVICE_NAME="${SERVICE_NAME:-all}"
    if [ ! -x "$DEPLOY_SCRIPT" ]; then
      echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG [ERROR] 배포 스크립트 없음: $DEPLOY_SCRIPT"
      exit 1
    fi
    "$DEPLOY_SCRIPT" 2>&1 | tee -a "$DEPLOY_LOG"
    EXIT_CODE=${PIPESTATUS[0]}
    if [ "$EXIT_CODE" -ne 0 ]; then
      echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG [ERROR] 배포 실패 (exit: $EXIT_CODE)"
      exit "$EXIT_CODE"
    fi
    echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG 배포 완료 → https://billcare.exdev.co.kr"
  else
    echo "$(date '+%Y-%m-%d %H:%M:%S') $HOOK_TAG $BRANCH_NAME — 배포 생략 (main만 자동 배포)"
  fi
done
