#!/bin/bash

# Deployment Script für Harheimer TC Website
# Sichert Produktivdaten vor dem Build und stellt sie danach wieder her

echo "=== Harheimer TC Deployment ==="
echo ""

# 1. BACKUP: Laufende Produktivdaten VOR allen Git-Operationen sichern
echo "1. Backing up current production data (pre-git)..."

# Fresh backup dir
rm -rf .backup
mkdir -p .backup

# Backup server data (JSON) und CSVs immer vom Dateisystem, nicht aus 'stash'
cp -a server/data .backup/data_backup 2>/dev/null || echo "   No server/data to backup"
mkdir -p .backup/public_data
cp -a public/data/*.csv .backup/public_data/ 2>/dev/null || echo "   No public CSVs to backup"

# 2. Handle local changes and Git Pull
echo "2. Handling local changes and pulling latest from git..."

# Check if there are merge conflicts first
if [ -n "$(git status --porcelain | grep '^UU\|^AA\|^DD')" ]; then
  echo "   Resolving existing merge conflicts..."
  git reset --hard HEAD
fi

# Stash any local changes (including production data)
echo "   Stashing local changes..."
git stash push -m "Production deployment stash $(date)"

# Pull latest changes
echo "   Pulling latest changes..."
git pull
if [ $? -ne 0 ]; then
  echo "ERROR: Git pull failed!"
  exit 1
fi

# Reset any accidental changes from stash restore (should be none now)
git reset --hard HEAD >/dev/null 2>&1

# 3. Install dependencies
echo ""
echo "3. Installing dependencies..."
npm install
if [ $? -ne 0 ]; then
  echo "ERROR: npm install failed!"
  exit 1
fi

# 4. Remove old build (but keep data!)
echo ""
echo "4. Removing old build output..."
rm -rf .output

# 5. Build
echo ""
echo "5. Building application..."
npm run build
if [ $? -ne 0 ]; then
  echo "ERROR: Build failed!"
  exit 1
fi

# 6. Restore Production Data (überschreibe Repo-Defaults mit Backup)
echo ""
echo "6. Restoring production data..."

# Stelle server/data vollständig wieder her (inkl. config.json, users.json, news.json, sessions.json, members.json, membership-applications)
if [ -d .backup/data_backup ]; then
  mkdir -p server/data
  cp -a .backup/data_backup/. server/data/
else
  echo "No server/data to restore"
fi

# Stelle alle CSVs wieder her
if ls .backup/public_data/*.csv >/dev/null 2>&1; then
  mkdir -p public/data
  cp -a .backup/public_data/*.csv public/data/
else
  echo "No public CSVs to restore"
fi

# 7. Cleanup backup and stash
echo ""
echo "7. Cleaning up backup and stash..."
rm -rf .backup

# Clear the deployment stash (keep other stashes)
echo "   Clearing deployment stash..."
git stash list | grep "Production deployment stash" | head -1 | cut -d: -f1 | xargs -r git stash drop

# 8. Restart PM2
echo ""
echo "8. Restarting PM2..."
pm2 restart harheimertc

echo ""
echo "=== Deployment completed successfully! ==="
echo "The application is now running with the latest code and your production data preserved."

