#!/bin/bash
# Restore script for Studio EinsZwoVier services
# Usage: ./restore.sh YYYYMMDD_HHMMSS

set -e

if [ -z "$1" ]; then
  echo "Usage: $0 BACKUP_DATE"
  echo "Example: $0 20251007_020000"
  exit 1
fi

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BACKUP_DIR="${BACKUP_DIR:-/path/to/backups/einszwovier}"
DATE=$1

echo "=== WARNING: This will OVERWRITE current data! ==="
echo "=== Press Ctrl+C within 10 seconds to cancel... ==="
sleep 10

echo "=== Starting restore from backup $DATE ==="
echo "Working directory: $SCRIPT_DIR"

# Stop all containers
echo "Stopping containers..."
cd "$SCRIPT_DIR"
docker compose down

# 1. Restore BookStack database
echo "Restoring BookStack database..."
docker compose up -d bookstack-mariadb
sleep 10  # Wait for MariaDB to start

zcat "$BACKUP_DIR/bookstack_db_$DATE.sql.gz" | \
  docker exec -i bookstack-mariadb mariadb \
    -u"${BOOKSTACK_DB_USERNAME:-bookstack}" \
    -p"${BOOKSTACK_DB_PASSWORD}" \
    "${BOOKSTACK_DB_DATABASE:-bookstack}"

# 2. Restore BookStack files
echo "Restoring BookStack files..."
tar -xzf "$BACKUP_DIR/bookstack_files_$DATE.tar.gz" -C "$SCRIPT_DIR"

# 3. Restore Matrix data
echo "Restoring Matrix data..."
rm -rf "$SCRIPT_DIR/matrix/data"
tar -xzf "$BACKUP_DIR/matrix_data_$DATE.tar.gz" -C "$SCRIPT_DIR"

# 4. Restore PDF uploads
echo "Restoring PDF uploads..."
rm -rf "$SCRIPT_DIR/data/uploads"
tar -xzf "$BACKUP_DIR/pdf_uploads_$DATE.tar.gz" -C "$SCRIPT_DIR"

# 5. Restore courses data (if exists)
if [ -f "$BACKUP_DIR/courses_$DATE.tar.gz" ]; then
  echo "Restoring courses data..."
  tar -xzf "$BACKUP_DIR/courses_$DATE.tar.gz" -C "$SCRIPT_DIR"
fi

# 6. Restore .env if needed
if [ -f "$BACKUP_DIR/env_$DATE.backup" ]; then
  echo "Environment file backup found (not automatically restored)"
  echo "To restore: cp $BACKUP_DIR/env_$DATE.backup $SCRIPT_DIR/.env"
fi

# Start all containers
echo "Starting all containers..."
docker compose up -d

echo "=== Restore completed at $(date) ==="
echo "Please verify all services are working correctly"
