#!/bin/bash
# Configuration Backup Script for WorkRoot Website
# Backs up critical config files and environment variables

set -e

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
BACKUP_DIR="$PROJECT_ROOT/backups/pre-deploy"
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="$BACKUP_DIR/config-$TIMESTAMP.tar.gz"
LOG_FILE="$PROJECT_ROOT/backups/backup.log"

# Colors
GREEN='\033[0;32m'
NC='\033[0m'

log() {
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] $1" | tee -a "$LOG_FILE"
}

mkdir -p "$BACKUP_DIR"

log "${GREEN}Starting configuration backup...${NC}"

# Configuration files to backup
CONFIG_FILES=(
    "astro.config.mjs"
    "tailwind.config.mjs"
    "playwright.config.ts"
    "tsconfig.json"
    "package.json"
    "package-lock.json"
    ".env"
    ".env.example"
    "src/middleware.ts"
    "src/content/config.ts"
)

# Filter out non-existent files
EXISTING_FILES=()
for file in "${CONFIG_FILES[@]}"; do
    if [ -e "$PROJECT_ROOT/$file" ]; then
        EXISTING_FILES+=("$file")
    fi
done

# Create backup
cd "$PROJECT_ROOT"
tar -czf "$BACKUP_FILE" "${EXISTING_FILES[@]}" 2>/dev/null

# Verify
if [ ! -f "$BACKUP_FILE" ]; then
    log "ERROR: Config backup failed"
    exit 1
fi

BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
log "${GREEN}Configuration backup completed${NC}"
log "Location: $BACKUP_FILE"
log "Size: $BACKUP_SIZE"

# Create latest symlink
ln -sf "$BACKUP_FILE" "$BACKUP_DIR/latest-config.tar.gz"

# Cleanup (keep last 10 config backups)
cd "$BACKUP_DIR"
ls -t config-*.tar.gz 2>/dev/null | tail -n +11 | xargs -r rm -f
log "Old config backups cleaned up (kept last 10)"

echo -e "${GREEN}✓ Configuration backup completed${NC}"
echo -e "  Location: $BACKUP_FILE"
echo -e "  Size: $BACKUP_SIZE"
