#!/bin/bash
set -e

if [ "${TAXBAIK_DEPLOY_FROM_CI:-}" != "1" ]; then
  echo "❌ This deployment script may only be run from CI." >&2
  exit 1
fi

DEPLOY_HOME="/home/kjh2064"
WEB_TIMESTAMP=$(TZ=Asia/Seoul date +%Y%m%d_%H%M%S)

echo "===== 🚀 TaxBaik 배포 스크립트 ====="
echo "Web Timestamp: $WEB_TIMESTAMP"

# Web 배포
echo "=== Deploying Web ==="
WEB_DEPLOY_DIR="$DEPLOY_HOME/deployments/taxbaik_${WEB_TIMESTAMP}"
mkdir -p "$WEB_DEPLOY_DIR"

if [ -z "$1" ]; then
  echo "Error: Publish directory required"
  exit 1
fi

# 첫 번째 인자는 publish 경로
cp -r "$1/web" "$WEB_DEPLOY_DIR/"
ln -sfn "$WEB_DEPLOY_DIR/web" "$DEPLOY_HOME/taxbaik_active"
echo "✓ Web symlink updated: $WEB_DEPLOY_DIR/web"

# 프로세스 재시작
echo "=== Restarting processes ==="
pkill -9 -f "TaxBaik.Web" || true
sleep 3

echo "=== Starting Web ==="
cd "$DEPLOY_HOME/taxbaik_active"
export ConnectionStrings__Default="Host=localhost;Database=taxbaikdb;Username=taxbaik;Password=taxbaik123"
export ASPNETCORE_ENVIRONMENT=Production
export ASPNETCORE_URLS=http://127.0.0.1:5001
nohup /usr/local/dotnet/dotnet TaxBaik.Web.dll > web.log 2>&1 &
sleep 2
ps aux | grep TaxBaik.Web | grep -v grep && echo "✓ Web started" || echo "✗ Web failed"

echo ""
echo "===== ✅ 배포 완료 ====="
cat "$DEPLOY_HOME/taxbaik_active/wwwroot/version.json" 2>/dev/null || echo "Version file not found"
