#!/bin/bash
# Backup script for Studio EinsZwoVier services
# Run daily via cron: 0 2 * * * /path/to/backup.sh

set -e

# 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=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=30

# Create backup directory
mkdir -p "$BACKUP_DIR"

echo "=== Starting backup at $(date) ==="
echo "Working directory: $SCRIPT_DIR"

# 1. Backup BookStack database
echo "Backing up BookStack database..."
docker exec bookstack-mariadb mariadb-dump \
  -u"${BOOKSTACK_DB_USERNAME:-bookstack}" \
  -p"${BOOKSTACK_DB_PASSWORD}" \
  "${BOOKSTACK_DB_DATABASE:-bookstack}" \
  | gzip > "$BACKUP_DIR/bookstack_db_$DATE.sql.gz"

# 2. Backup BookStack uploads and config
echo "Backing up BookStack files..."
tar -czf "$BACKUP_DIR/bookstack_files_$DATE.tar.gz" \
  -C "$SCRIPT_DIR" \
  bookstack/bookstack_app_data/www/uploads \
  bookstack/bookstack_app_data/www/images \
  bookstack/bookstack_app_data/www/files

# 3. Backup Matrix data (includes homeserver.db)
echo "Backing up Matrix server data..."
tar -czf "$BACKUP_DIR/matrix_data_$DATE.tar.gz" \
  -C "$SCRIPT_DIR" \
  matrix/data

# 4. Backup PDF uploads
echo "Backing up PDF uploads..."
tar -czf "$BACKUP_DIR/pdf_uploads_$DATE.tar.gz" \
  -C "$SCRIPT_DIR" \
  data/uploads

# 5. Backup courses CSV
echo "Backing up courses data..."
tar -czf "$BACKUP_DIR/courses_$DATE.tar.gz" \
  -C "$SCRIPT_DIR" \
  data/courses.csv \
  static/images/courses

# 6. Backup .env file (IMPORTANT: Contains secrets!)
echo "Backing up environment configuration..."
cp "$SCRIPT_DIR/.env" "$BACKUP_DIR/env_$DATE.backup"
chmod 600 "$BACKUP_DIR/env_$DATE.backup"

# 7. Remove old backups (older than RETENTION_DAYS)
echo "Cleaning up old backups..."
find "$BACKUP_DIR" -type f -mtime +$RETENTION_DAYS -delete

echo "=== Backup completed at $(date) ==="
echo "Backup location: $BACKUP_DIR"
ls -lh "$BACKUP_DIR" | tail -10
