#!/usr/bin/env bash
# 로컬 site 배포 — GitHub CI 우회. build → S3 sync → CloudFront 무효화.
# 기준: origin/<env> 브랜치의 최신 커밋(푸시된 것). 앱은 front/ 서브디렉토리.
# 사용: ./deploy-site.sh <stg|prod>
# 준비물: AWS 자격증명(배포권한), node, git, aws cli — README.md 참고
set -euo pipefail

ENV="${1:?사용: deploy-site.sh <stg|prod>}"
[[ "$ENV" =~ ^(stg|prod)$ ]] || { echo "env는 stg|prod 만 가능"; exit 1; }

export AWS_PROFILE="${AWS_PROFILE:-insuniverse-readonly}"
export AWS_REGION="${AWS_REGION:-ap-northeast-2}"
export AWS_DEFAULT_REGION="$AWS_REGION"

REPO="$(git -C "$(dirname "$(realpath "$0")")" rev-parse --show-toplevel)"
# 버킷·env 경로는 CI 워크플로에서 그대로 읽음 (site는 버킷명이 env마다 불규칙: stg=s.insuniverse.com / prod=insuniverse-prod-site)
WF="$REPO/.github/workflows/$ENV.yml"
BUCKET="$(grep -E '^\s*S3_BUCKET:' "$WF" | head -1 | awk '{print $2}')"
ENV_URI="$(grep -E '^\s*ENV_S3_URI:' "$WF" | head -1 | awk '{print $2}')"
[ -n "$BUCKET" ] && [ -n "$ENV_URI" ] || { echo "❌ 워크플로($WF)에서 버킷/ENV 못 읽음"; exit 1; }
WT="/tmp/iu-site-$ENV-deploy"
SUBDIR="front"   # 실제 앱 위치 (workflow working-directory)

echo "▶ [$ENV] site 배포 (profile=$AWS_PROFILE)"
cd "$REPO"
git fetch origin -q "+refs/heads/$ENV:refs/remotes/origin/$ENV"
if git -C "$WT" rev-parse 2>/dev/null; then
  git -C "$WT" reset --hard "origin/$ENV" >/dev/null
else
  git worktree add -q "$WT" "origin/$ENV"
fi
APP="$WT/$SUBDIR"
# node_modules 재사용(빠른 빌드). 없으면 npm install (workflow와 동일).
if [ ! -d "$APP/node_modules" ]; then
  if [ -d "$REPO/$SUBDIR/node_modules" ]; then ln -sf "$REPO/$SUBDIR/node_modules" "$APP/node_modules"
  else (cd "$APP" && npm install >/tmp/iu-site-npm-$ENV.log 2>&1); fi
fi
cd "$APP"
echo "  커밋: $(git -C "$WT" rev-parse --short HEAD)"
aws s3 cp "$ENV_URI" .env >/dev/null
echo "  빌드..."
npm run build >"/tmp/iu-site-build-$ENV.log" 2>&1 \
  || { echo "❌ 빌드 실패: /tmp/iu-site-build-$ENV.log"; tail -20 "/tmp/iu-site-build-$ENV.log"; exit 1; }
echo "  S3 동기화..."
aws s3 sync ./dist "s3://$BUCKET" --delete --exclude index.html >/dev/null
aws s3 cp ./dist/index.html "s3://$BUCKET/index.html" --cache-control "no-cache, no-store, must-revalidate" >/dev/null
DIST="$(aws cloudfront list-distributions --query "DistributionList.Items[?contains(Origins.Items[0].DomainName,'$BUCKET')].Id" --output text)"
aws cloudfront create-invalidation --distribution-id "$DIST" --paths "/*" --query 'Invalidation.Id' --output text >/dev/null
echo "✅ [$ENV] site 배포 완료 (CloudFront $DIST 무효화, 커밋 $(git -C "$WT" rev-parse --short HEAD))"
