#!/bin/bash
# Quant Engine Manual Deployment Script (v9)
# 환경: hz-prod-01 (178.104.200.7/172.17.0.1)
# 배포 경로: /home/kjh2064/quantengine_active
# 서비스: quantengine (systemd)

set -e

# ═══════════════════════════════════════════════════════════════
# 설정
# ═══════════════════════════════════════════════════════════════

DEPLOY_HOST="${1:-178.104.200.7}"
DEPLOY_USER="kjh2064"
SSH_KEY="${HOME}/.ssh/id_ed25519"
LOCAL_PUBLISH_DIR="$(pwd)/src/dotnet/QuantEngine.Web/publish"
REMOTE_DEPLOY_PATH="/home/kjh2064/quantengine_active"
REMOTE_BACKUP_PATH="/home/kjh2064/quantengine_backup"
SERVICE_NAME="quantengine"

echo "🚀 Quant Engine v9 Manual Deployment"
echo "═══════════════════════════════════════════════════════════════"
echo "Deploy Host:   $DEPLOY_HOST"
echo "Deploy User:   $DEPLOY_USER"
echo "Local Path:    $LOCAL_PUBLISH_DIR"
echo "Remote Path:   $REMOTE_DEPLOY_PATH"
echo "Backup Path:   $REMOTE_BACKUP_PATH"
echo "Service:       $SERVICE_NAME"
echo "Public URL:    http://178.104.200.7/quant/"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# ═══════════════════════════════════════════════════════════════
# Step 1: SSH 연결 확인
# ═══════════════════════════════════════════════════════════════

echo "📊 Step 1: SSH 연결 및 환경 파악..."

ssh -i "$SSH_KEY" "$DEPLOY_USER@$DEPLOY_HOST" << 'ENVCHECK'
echo "✓ SSH 연결 성공"
echo ""
echo "시스템 정보:"
hostname
uname -a
echo ""

echo "디스크 상태:"
df -h | grep -E "^/dev|Filesystem|/$"
echo ""

echo "서비스 상태:"
sudo systemctl status "$SERVICE_NAME" --no-pager 2>/dev/null | grep -E "Active:|Loaded:" || echo "⚠️ 서비스 상태 확인 필요"
echo ""

echo "배포 디렉토리:"
if [ -d "/home/kjh2064/quantengine_active" ]; then
  echo "✓ /home/kjh2064/quantengine_active 존재"
  ls -lh /home/kjh2064/quantengine_active | head -5
  echo "..."
else
  echo "✗ /home/kjh2064/quantengine_active 없음 (첫 배포)"
fi
echo ""

echo "Nginx 포트 확인:"
sudo netstat -tuln 2>/dev/null | grep ":80\|:443" || echo "⚠️ 포트 확인 필요"
echo ""

echo "Nginx 설정:"
cat /etc/nginx/sites-available/gitea-ip.conf | grep -A 5 "location /quant" || echo "⚠️ Nginx 설정 확인 필요"
ENVCHECK

echo ""

# ═══════════════════════════════════════════════════════════════
# Step 2: 배포 파일 준비 확인
# ═══════════════════════════════════════════════════════════════

echo "📦 Step 2: 배포 파일 확인..."

if [ ! -d "$LOCAL_PUBLISH_DIR" ]; then
  echo "❌ 오류: $LOCAL_PUBLISH_DIR 없음"
  echo "먼저 'dotnet publish -c Release'를 실행하세요"
  exit 1
fi

PACKAGE_SIZE=$(du -sh "$LOCAL_PUBLISH_DIR" | cut -f1)
FILE_COUNT=$(find "$LOCAL_PUBLISH_DIR" -type f | wc -l)

echo "✓ 배포 패키지:"
echo "  크기: $PACKAGE_SIZE"
echo "  파일 수: $FILE_COUNT"
echo ""

# ═══════════════════════════════════════════════════════════════
# Step 3: 사전 확인
# ═══════════════════════════════════════════════════════════════

echo "✅ 배포 전 확인 사항:"
echo "  [ ] Release 빌드 완료됨"
echo "  [ ] publish 폴더 확인됨 ($PACKAGE_SIZE)"
echo "  [ ] SSH 키 설정됨 ($SSH_KEY)"
echo ""

read -p "배포를 진행하시겠습니까? (y/n) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "❌ 배포 취소됨"
  exit 1
fi

echo ""

# ═══════════════════════════════════════════════════════════════
# Step 4: 서비스 중지 및 백업 생성
# ═══════════════════════════════════════════════════════════════

echo "💾 Step 3: 서비스 중지 및 백업 생성..."

ssh -i "$SSH_KEY" "$DEPLOY_USER@$DEPLOY_HOST" << 'BACKUP'
set -e

SERVICE_NAME="quantengine"
DEPLOY_PATH="/home/kjh2064/quantengine_active"
BACKUP_DIR="/home/kjh2064/quantengine_backup"
BACKUP_NAME="quantengine_$(date +%Y%m%d_%H%M%S)"

echo "  서비스 중지 중..."
sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || true
sleep 2
echo "  ✓ 서비스 중지"

mkdir -p "$BACKUP_DIR"
if [ -d "$DEPLOY_PATH" ]; then
  cp -r "$DEPLOY_PATH" "$BACKUP_DIR/$BACKUP_NAME"
  echo "✓ 백업 생성: $BACKUP_DIR/$BACKUP_NAME"

  # 최근 5개만 유지
  BACKUP_COUNT=$(ls -1 "$BACKUP_DIR" | wc -l)
  if [ "$BACKUP_COUNT" -gt 5 ]; then
    OLD_BACKUPS=$(ls -1t "$BACKUP_DIR" | tail -n +6)
    for backup in $OLD_BACKUPS; do
      rm -rf "$BACKUP_DIR/$backup"
      echo "🧹 오래된 백업 삭제: $backup"
    done
  fi
else
  echo "⚠️ 기존 배포 없음 (첫 배포)"
  mkdir -p "$DEPLOY_PATH"
fi
BACKUP

echo ""

# ═══════════════════════════════════════════════════════════════
# Step 5: 파일 전송
# ═══════════════════════════════════════════════════════════════

echo "📤 Step 4: 파일 전송 (rsync)..."

rsync -avz --delete \
  --rsh="ssh -i $SSH_KEY" \
  "$LOCAL_PUBLISH_DIR/" \
  "$DEPLOY_USER@$DEPLOY_HOST:$REMOTE_DEPLOY_PATH/"

echo "✓ 파일 전송 완료"
echo ""

# ═══════════════════════════════════════════════════════════════
# Step 6: 권한 설정 및 서비스 재시작
# ═══════════════════════════════════════════════════════════════

echo "🔧 Step 5: 파일 검증 및 서비스 시작..."

ssh -i "$SSH_KEY" "$DEPLOY_USER@$DEPLOY_HOST" << 'FINALIZE'
set -e

SERVICE_NAME="quantengine"
DEPLOY_PATH="/home/kjh2064/quantengine_active"

echo "  파일 검증 중..."
if [ -f "$DEPLOY_PATH/QuantEngine.Web.dll" ]; then
  echo "  ✓ QuantEngine.Web.dll 확인됨"
else
  echo "  ❌ QuantEngine.Web.dll 없음 (배포 실패)"
  exit 1
fi

echo "  서비스 시작 중..."
sudo systemctl start "$SERVICE_NAME" 2>/dev/null || echo "  ⚠️ 서비스 시작 실패"
sleep 3

if sudo systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
  echo "  ✓ $SERVICE_NAME 시작 완료"
else
  echo "  ⚠️ 서비스 상태 확인"
  sudo systemctl status "$SERVICE_NAME" || true
fi
FINALIZE

echo ""

# ═══════════════════════════════════════════════════════════════
# Step 7: 헬스 체크
# ═══════════════════════════════════════════════════════════════

echo "🧪 Step 6: 헬스 체크..."

for i in {1..30}; do
  HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
    "http://$DEPLOY_HOST/quant/" 2>/dev/null || echo "000")

  if [ "$HTTP_CODE" = "200" ]; then
    echo "✓ Health check PASS (HTTP 200)"
    break
  fi

  echo "  시도 $i/30: HTTP $HTTP_CODE (대기 중...)"
  sleep 2
done

echo ""

# ═══════════════════════════════════════════════════════════════
# 배포 완료
# ═══════════════════════════════════════════════════════════════

echo "═══════════════════════════════════════════════════════════════"
echo "✅ 배포 완료!"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "📊 배포 정보:"
echo "  공인 URL: http://$DEPLOY_HOST/quant/"
echo "  배포 경로: $REMOTE_DEPLOY_PATH"
echo "  백업 경로: $REMOTE_BACKUP_PATH"
echo "  서비스: $SERVICE_NAME"
echo "  패키지 크기: $PACKAGE_SIZE"
echo ""
echo "🌐 구조:"
echo "  Nginx: reverse proxy /quant/ → localhost:5000"
echo "  설정: /etc/nginx/sites-available/gitea-ip.conf"
echo ""
echo "🔍 로그 확인:"
echo "  ssh -i $SSH_KEY $DEPLOY_USER@$DEPLOY_HOST 'sudo journalctl -u $SERVICE_NAME -f'"
echo ""
echo "🔄 롤백 (필요시):"
echo "  ssh -i $SSH_KEY $DEPLOY_USER@$DEPLOY_HOST << 'EOF'"
echo "  LATEST=\$(ls -t $REMOTE_BACKUP_PATH | head -1)"
echo "  cp -r $REMOTE_BACKUP_PATH/\$LATEST/* $REMOTE_DEPLOY_PATH/"
echo "  sudo systemctl restart $SERVICE_NAME"
echo "  EOF"
echo ""
