#!/bin/bash
# Full Backup Script for WorkRoot Website
# Backs up all critical files: content, source, configs, environment

set -e  # Exit on error

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

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

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

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

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

# Files and directories to backup
BACKUP_ITEMS=(
    "src/"
    "public/"
    "astro.config.mjs"
    "tailwind.config.mjs"
    "playwright.config.ts"
    "package.json"
    "package-lock.json"
    ".env"
    ".env.example"
    "tsconfig.json"
    "DEPLOYMENT.md"
    "README.md"
    ".agents/"
)

# Files to exclude
EXCLUDE_PATTERNS=(
    "node_modules"
    "dist"
    ".astro"
    "test-results"
    ".git"
    "backups"
    "*.log"
)

# Build exclude arguments
EXCLUDE_ARGS=""
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
    EXCLUDE_ARGS="$EXCLUDE_ARGS --exclude=$pattern"
done

# Verify critical files exist
log "Verifying critical files..."
CRITICAL_FILES=("src/" "package.json" "astro.config.mjs")
for file in "${CRITICAL_FILES[@]}"; do
    if [ ! -e "$PROJECT_ROOT/$file" ]; then
        log "${RED}ERROR: Critical file/directory missing: $file${NC}"
        exit 1
    fi
done

# Create backup
log "Creating backup archive: $BACKUP_FILE"
cd "$PROJECT_ROOT"
tar -czf "$BACKUP_FILE" $EXCLUDE_ARGS "${BACKUP_ITEMS[@]}" 2>/dev/null || {
    log "${RED}ERROR: Backup creation failed${NC}"
    exit 1
}

# Verify backup was created
if [ ! -f "$BACKUP_FILE" ]; then
    log "${RED}ERROR: Backup file was not created${NC}"
    exit 1
fi

# Get backup size
BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
log "${GREEN}Backup created successfully${NC}"
log "Backup file: $BACKUP_FILE"
log "Backup size: $BACKUP_SIZE"

# Verify backup integrity
log "Verifying backup integrity..."
tar -tzf "$BACKUP_FILE" > /dev/null 2>&1 || {
    log "${RED}ERROR: Backup verification failed - archive is corrupted${NC}"
    rm "$BACKUP_FILE"
    exit 1
}

log "${GREEN}Backup integrity verified${NC}"

# Count files in backup
FILE_COUNT=$(tar -tzf "$BACKUP_FILE" | wc -l)
log "Files backed up: $FILE_COUNT"

# Create latest symlink
LATEST_LINK="$BACKUP_DIR/latest-full.tar.gz"
ln -sf "$BACKUP_FILE" "$LATEST_LINK"
log "Latest backup link created: $LATEST_LINK"

# Cleanup old backups (keep last 7 days)
log "Cleaning up old daily backups (keeping last 7)..."
cd "$BACKUP_DIR"
ls -t full-backup-*.tar.gz 2>/dev/null | tail -n +8 | xargs -r rm -f
log "Cleanup completed"

# Weekly backup (if Sunday)
if [ "$(date +%u)" -eq 7 ]; then
    WEEKLY_DIR="$PROJECT_ROOT/backups/weekly"
    mkdir -p "$WEEKLY_DIR"
    WEEKLY_FILE="$WEEKLY_DIR/weekly-backup-$(date +%Y-%m-%d).tar.gz"
    cp "$BACKUP_FILE" "$WEEKLY_FILE"
    log "${GREEN}Weekly backup created: $WEEKLY_FILE${NC}"

    # Cleanup old weekly backups (keep last 4 weeks)
    cd "$WEEKLY_DIR"
    ls -t weekly-backup-*.tar.gz 2>/dev/null | tail -n +5 | xargs -r rm -f
fi

# Monthly backup (if 1st of month)
if [ "$(date +%d)" -eq 1 ]; then
    MONTHLY_DIR="$PROJECT_ROOT/backups/monthly"
    mkdir -p "$MONTHLY_DIR"
    MONTHLY_FILE="$MONTHLY_DIR/monthly-backup-$(date +%Y-%m).tar.gz"
    cp "$BACKUP_FILE" "$MONTHLY_FILE"
    log "${GREEN}Monthly backup created: $MONTHLY_FILE${NC}"

    # Cleanup old monthly backups (keep last 3 months)
    cd "$MONTHLY_DIR"
    ls -t monthly-backup-*.tar.gz 2>/dev/null | tail -n +4 | xargs -r rm -f
fi

log "${GREEN}Full backup completed successfully${NC}"
echo ""
echo -e "${GREEN}✓ Backup completed${NC}"
echo -e "  Location: $BACKUP_FILE"
echo -e "  Size: $BACKUP_SIZE"
echo -e "  Files: $FILE_COUNT"
