#!/bin/bash
# SamCloud Music - Automated Backup Script
# Version: 1.0.0
# Created: July 1, 2025
# Purpose: Create comprehensive backups of the SamCloud Music project

set -e  # Exit on any error

# Configuration
PROJECT_NAME="SamCloud Music"
BACKUP_BASE_DIR="/Volumes/SamMgmt/Containers/SpotSpot/Backup"
SOURCE_DIR="/Volumes/SamMgmt/Containers/SamCloud Music"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="SamCloud_Music_${TIMESTAMP}"
BACKUP_DIR="${BACKUP_BASE_DIR}/${BACKUP_NAME}"

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

# Logging
LOG_FILE="${BACKUP_DIR}/backup.log"

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

error() {
    echo -e "${RED}[ERROR]${NC} $1" | tee -a "${LOG_FILE}"
}

success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1" | tee -a "${LOG_FILE}"
}

warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1" | tee -a "${LOG_FILE}"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1" | tee -a "${LOG_FILE}"
}

# Function to check prerequisites
check_prerequisites() {
    info "Checking prerequisites..."
    
    # Check if source directory exists
    if [ ! -d "$SOURCE_DIR" ]; then
        error "Source directory does not exist: $SOURCE_DIR"
        exit 1
    fi
    
    # Check if backup base directory exists, create if not
    if [ ! -d "$BACKUP_BASE_DIR" ]; then
        warning "Backup base directory does not exist, creating: $BACKUP_BASE_DIR"
        mkdir -p "$BACKUP_BASE_DIR"
    fi
    
    # Check available disk space (require at least 1GB free)
    AVAILABLE_SPACE=$(df -h "$BACKUP_BASE_DIR" | awk 'NR==2 {print $4}' | sed 's/[^0-9]//g')
    if [ "$AVAILABLE_SPACE" -lt 1000000 ]; then  # 1GB in KB
        warning "Low disk space available. Backup may fail if project is large."
    fi
    
    success "Prerequisites check completed"
}

# Function to stop container if running
stop_container() {
    info "Checking container status..."
    
    cd "$SOURCE_DIR"
    if docker-compose ps | grep -q "Up"; then
        info "Stopping Docker container for safe backup..."
        docker-compose stop
        CONTAINER_WAS_RUNNING=true
    else
        info "Container not running, proceeding with backup"
        CONTAINER_WAS_RUNNING=false
    fi
}

# Function to create backup directory structure
create_backup_structure() {
    info "Creating backup directory structure..."
    
    mkdir -p "$BACKUP_DIR"
    mkdir -p "${BACKUP_DIR}/docs"
    mkdir -p "${BACKUP_DIR}/logs"
    
    # Create initial log file
    touch "$LOG_FILE"
    
    success "Backup directory created: $BACKUP_DIR"
}

# Function to copy project files
copy_project_files() {
    info "Copying project files..."
    
    # Copy all project files except large/unnecessary items
    rsync -av \
        --exclude='*.log' \
        --exclude='__pycache__/' \
        --exclude='.git/' \
        --exclude='node_modules/' \
        --exclude='*.pyc' \
        --exclude='.DS_Store' \
        --exclude='backend/downloads/*' \
        --exclude='temp/*' \
        --progress \
        "$SOURCE_DIR/" "$BACKUP_DIR/" 2>&1 | tee -a "$LOG_FILE"
    
    if [ $? -eq 0 ]; then
        success "Project files copied successfully"
    else
        error "Failed to copy project files"
        exit 1
    fi
}

# Function to create backup manifest
create_manifest() {
    info "Creating backup manifest..."
    
    MANIFEST_FILE="${BACKUP_DIR}/BACKUP_MANIFEST.md"
    
    cat > "$MANIFEST_FILE" << EOF
# SamCloud Music Backup Manifest

**Backup Created**: $(date)  
**Backup Name**: $BACKUP_NAME  
**Source**: $SOURCE_DIR  
**Backup Location**: $BACKUP_DIR  

## Backup Contents

### Project Structure
\`\`\`
$(find "$BACKUP_DIR" -type d | head -20 | sed "s|$BACKUP_DIR||g")
\`\`\`

### File Count by Type
\`\`\`
$(find "$BACKUP_DIR" -type f | grep -E '\.(py|js|html|css|md|yml|yaml|json|txt|sh)$' | wc -l) source files
$(find "$BACKUP_DIR" -type f | grep -E '\.(py)$' | wc -l) Python files
$(find "$BACKUP_DIR" -type f | grep -E '\.(js|html|css)$' | wc -l) Web files
$(find "$BACKUP_DIR" -type f | grep -E '\.(md)$' | wc -l) Documentation files
$(find "$BACKUP_DIR" -type f | grep -E '\.(yml|yaml|json)$' | wc -l) Configuration files
\`\`\`

### Key Files
- **Main Application**: backend/spotspot.py ($(wc -l < "$BACKUP_DIR/backend/spotspot.py" 2>/dev/null || echo "N/A") lines)
- **Frontend Template**: backend/templates/index.html ($(wc -l < "$BACKUP_DIR/backend/templates/index.html" 2>/dev/null || echo "N/A") lines)
- **Docker Configuration**: docker-compose.yml
- **Environment**: .env (credentials secured)
- **Documentation**: docs/ folder with complete guides

### System State
- **Container Status**: $(if [ "$CONTAINER_WAS_RUNNING" = true ]; then echo "Was running (stopped for backup)"; else echo "Not running"; fi)
- **Backup Size**: $(du -sh "$BACKUP_DIR" | cut -f1)
- **Total Files**: $(find "$BACKUP_DIR" -type f | wc -l) files
- **Total Directories**: $(find "$BACKUP_DIR" -type d | wc -l) directories

## Recovery Instructions

### Quick Recovery
\`\`\`bash
# Stop current deployment
cd "/Volumes/SamMgmt/Containers/SamCloud Music"
docker-compose down

# Restore from this backup
cd "/Volumes/SamMgmt/Containers"
rm -rf "SamCloud Music"
cp -R "$BACKUP_DIR" "SamCloud Music"

# Restart application
cd "SamCloud Music"
docker-compose up --build
\`\`\`

### Selective Recovery
\`\`\`bash
# Restore specific files only
cp "$BACKUP_DIR/backend/spotspot.py" "/Volumes/SamMgmt/Containers/SamCloud Music/backend/"
cp "$BACKUP_DIR/backend/templates/index.html" "/Volumes/SamMgmt/Containers/SamCloud Music/backend/templates/"
cp "$BACKUP_DIR/docker-compose.yml" "/Volumes/SamMgmt/Containers/SamCloud Music/"
\`\`\`

## Verification Checklist
- [ ] Web interface loads at http://localhost:6544
- [ ] Container starts without errors
- [ ] Search functionality works
- [ ] Download system operational  
- [ ] Library connection possible
- [ ] All tabs navigate properly

## Notes
$(if [ -f "$SOURCE_DIR/DEVELOPMENT_LOG.md" ]; then echo "- Development log included with latest progress"; fi)
$(if [ -f "$SOURCE_DIR/.env" ]; then echo "- Environment configuration preserved"; fi)
$(if [ -d "$SOURCE_DIR/docs" ]; then echo "- Complete documentation included"; fi)

---
**Backup Tool Version**: 1.0.0  
**Backup Integrity**: $(if [ -f "$BACKUP_DIR/backend/spotspot.py" ] && [ -f "$BACKUP_DIR/docker-compose.yml" ]; then echo "✅ Verified"; else echo "❌ Failed"; fi)
EOF

    success "Backup manifest created: $MANIFEST_FILE"
}

# Function to create verification report
create_verification() {
    info "Creating verification report..."
    
    VERIFICATION_FILE="${BACKUP_DIR}/VERIFICATION_REPORT.txt"
    
    cat > "$VERIFICATION_FILE" << EOF
SamCloud Music Backup Verification Report
Generated: $(date)

CRITICAL FILES CHECK:
$(echo "✓ Main Flask app" && ls -la "$BACKUP_DIR/backend/spotspot.py" 2>/dev/null || echo "✗ Missing backend/spotspot.py")
$(echo "✓ Frontend template" && ls -la "$BACKUP_DIR/backend/templates/index.html" 2>/dev/null || echo "✗ Missing backend/templates/index.html")
$(echo "✓ Docker config" && ls -la "$BACKUP_DIR/docker-compose.yml" 2>/dev/null || echo "✗ Missing docker-compose.yml")
$(echo "✓ Environment file" && ls -la "$BACKUP_DIR/.env" 2>/dev/null || echo "✗ Missing .env")
$(echo "✓ Requirements" && ls -la "$BACKUP_DIR/requirements.txt" 2>/dev/null || echo "✗ Missing requirements.txt")

DOCUMENTATION CHECK:
$(echo "✓ Master documentation" && ls -la "$BACKUP_DIR/docs/README.md" 2>/dev/null || echo "✗ Missing docs/README.md")
$(echo "✓ Progress log" && ls -la "$BACKUP_DIR/docs/development/progress-log.md" 2>/dev/null || echo "✗ Missing progress log")
$(echo "✓ Architecture docs" && ls -la "$BACKUP_DIR/docs/technical/architecture.md" 2>/dev/null || echo "✗ Missing architecture docs")
$(echo "✓ Known issues" && ls -la "$BACKUP_DIR/docs/troubleshooting/known-issues.md" 2>/dev/null || echo "✗ Missing known issues")

SERVICE FILES CHECK:
$(find "$BACKUP_DIR/backend/services" -name "*.py" 2>/dev/null | wc -l) service files found
$(echo "✓ Config service" && ls -la "$BACKUP_DIR/backend/services/config_service.py" 2>/dev/null || echo "✗ Missing config service")
$(echo "✓ Download service" && ls -la "$BACKUP_DIR/backend/services/download_service.py" 2>/dev/null || echo "✗ Missing download service")
$(echo "✓ Jellyfin service" && ls -la "$BACKUP_DIR/backend/services/jellyfin_service.py" 2>/dev/null || echo "✗ Missing jellyfin service")

BACKUP INTEGRITY:
Total size: $(du -sh "$BACKUP_DIR" | cut -f1)
File count: $(find "$BACKUP_DIR" -type f | wc -l)
Directory count: $(find "$BACKUP_DIR" -type d | wc -l)
Largest files:
$(find "$BACKUP_DIR" -type f -exec ls -la {} \; | sort -nr -k5 | head -5)

BACKUP STATUS: $(if [ -f "$BACKUP_DIR/backend/spotspot.py" ] && [ -f "$BACKUP_DIR/docker-compose.yml" ] && [ -f "$BACKUP_DIR/.env" ]; then echo "✅ COMPLETE"; else echo "❌ INCOMPLETE"; fi)
EOF

    success "Verification report created: $VERIFICATION_FILE"
}

# Function to restart container if it was running
restart_container() {
    if [ "$CONTAINER_WAS_RUNNING" = true ]; then
        info "Restarting Docker container..."
        cd "$SOURCE_DIR"
        docker-compose start
        
        # Wait for container to be ready
        sleep 5
        
        if docker-compose ps | grep -q "Up"; then
            success "Container restarted successfully"
        else
            warning "Container may not have started properly. Check with: docker-compose ps"
        fi
    fi
}

# Function to cleanup old backups (keep last 10)
cleanup_old_backups() {
    info "Cleaning up old backups (keeping last 10)..."
    
    cd "$BACKUP_BASE_DIR"
    
    # Count SamCloud Music backups
    BACKUP_COUNT=$(ls -1 | grep "^SamCloud_Music_" | wc -l)
    
    if [ "$BACKUP_COUNT" -gt 10 ]; then
        EXCESS_COUNT=$((BACKUP_COUNT - 10))
        info "Found $BACKUP_COUNT backups, removing oldest $EXCESS_COUNT"
        
        # Remove oldest backups
        ls -1t | grep "^SamCloud_Music_" | tail -n "$EXCESS_COUNT" | xargs rm -rf
        
        success "Cleaned up $EXCESS_COUNT old backups"
    else
        info "Only $BACKUP_COUNT backups found, no cleanup needed"
    fi
}

# Function to display summary
display_summary() {
    echo ""
    echo "================================================================"
    success "BACKUP COMPLETED SUCCESSFULLY"
    echo "================================================================"
    echo ""
    info "Backup Details:"
    echo "  • Name: $BACKUP_NAME"
    echo "  • Location: $BACKUP_DIR"
    echo "  • Size: $(du -sh "$BACKUP_DIR" | cut -f1)"
    echo "  • Files: $(find "$BACKUP_DIR" -type f | wc -l)"
    echo "  • Created: $(date)"
    echo ""
    info "Quick Recovery Command:"
    echo "  cd '/Volumes/SamMgmt/Containers' && rm -rf 'SamCloud Music' && cp -R '$BACKUP_DIR' 'SamCloud Music'"
    echo ""
    info "Backup Files:"
    echo "  • Manifest: ${BACKUP_DIR}/BACKUP_MANIFEST.md"
    echo "  • Verification: ${BACKUP_DIR}/VERIFICATION_REPORT.txt"
    echo "  • Log: ${BACKUP_DIR}/backup.log"
    echo ""
    success "Backup process completed successfully!"
}

# Main execution
main() {
    info "Starting SamCloud Music backup process..."
    info "Timestamp: $(date)"
    info "Source: $SOURCE_DIR"
    info "Destination: $BACKUP_DIR"
    
    check_prerequisites
    create_backup_structure
    stop_container
    copy_project_files
    create_manifest
    create_verification
    restart_container
    cleanup_old_backups
    display_summary
}

# Run main function
main "$@"
