#!/bin/bash

# Branch Filtering Production Deployment Script
# This script automates the deployment of branch filtering fixes

set -e  # Exit on any error

# Configuration
BACKUP_DIR="../backup_$(date +%Y%m%d_%H%M%S)"
LOG_FILE="deployment_$(date +%Y%m%d_%H%M%S).log"

# 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 function
log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}

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

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

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

# Function to check if running as appropriate user
check_user() {
    if [[ $EUID -eq 0 ]]; then
        log_warning "Running as root. Consider running as web server user."
    fi
}

# Function to create backup
create_backup() {
    log "Creating backup of current deployment..."
    
    if cp -r . "$BACKUP_DIR"; then
        log_success "Backup created: $BACKUP_DIR"
        return 0
    else
        log_error "Failed to create backup"
        return 1
    fi
}

# Function to check prerequisites
check_prerequisites() {
    log "Checking prerequisites..."
    
    # Check if Python is available
    if ! command -v python3 &> /dev/null; then
        log_error "Python3 is not installed or not in PATH"
        return 1
    fi
    
    # Check if Django project exists
    if [[ ! -f "manage.py" ]]; then
        log_error "manage.py not found. Are you in the Django project directory?"
        return 1
    fi
    
    # Check if required files exist
    required_files=(
        "production_branch_filtering_deployment.py"
        "rollback_branch_filtering.py"
    )
    
    for file in "${required_files[@]}"; do
        if [[ ! -f "$file" ]]; then
            log_error "Required file not found: $file"
            return 1
        fi
    done
    
    log_success "Prerequisites check passed"
    return 0
}

# Function to run deployment verification
run_deployment_verification() {
    log "Running deployment verification..."
    
    if python3 production_branch_filtering_deployment.py; then
        log_success "Deployment verification passed"
        return 0
    else
        log_error "Deployment verification failed"
        return 1
    fi
}

# Function to restart web services
restart_services() {
    log "Restarting web services..."
    
    # List of common web services
    services=("apache2" "nginx" "gunicorn")
    restarted_any=false
    
    for service in "${services[@]}"; do
        if systemctl is-active --quiet "$service" 2>/dev/null; then
            log "Restarting $service..."
            if sudo systemctl restart "$service"; then
                log_success "$service restarted successfully"
                restarted_any=true
            else
                log_warning "Failed to restart $service"
            fi
        fi
    done
    
    if [[ "$restarted_any" == false ]]; then
        log_warning "No web services were restarted. You may need to restart manually."
    fi
}

# Function to collect static files (if needed)
collect_static() {
    log "Collecting static files..."
    
    if python3 manage.py collectstatic --noinput; then
        log_success "Static files collected"
    else
        log_warning "Failed to collect static files (may not be configured)"
    fi
}

# Function to run Django checks
run_django_checks() {
    log "Running Django system checks..."
    
    if python3 manage.py check; then
        log_success "Django checks passed"
        return 0
    else
        log_error "Django checks failed"
        return 1
    fi
}

# Main deployment function
deploy() {
    log "=========================================="
    log "BRANCH FILTERING PRODUCTION DEPLOYMENT"
    log "=========================================="
    
    # Check user
    check_user
    
    # Check prerequisites
    if ! check_prerequisites; then
        log_error "Prerequisites check failed. Aborting deployment."
        exit 1
    fi
    
    # Create backup
    if ! create_backup; then
        log_error "Backup creation failed. Aborting deployment."
        exit 1
    fi
    
    # Run Django checks
    if ! run_django_checks; then
        log_error "Django checks failed. Aborting deployment."
        exit 1
    fi
    
    # Collect static files
    collect_static
    
    # Run deployment verification
    if ! run_deployment_verification; then
        log_error "Deployment verification failed."
        echo
        echo "Would you like to rollback? (y/n)"
        read -r rollback_choice
        if [[ "$rollback_choice" == "y" || "$rollback_choice" == "Y" ]]; then
            log "Starting rollback..."
            python3 rollback_branch_filtering.py
        fi
        exit 1
    fi
    
    # Restart services
    restart_services
    
    # Final verification
    log "Running final verification..."
    if run_deployment_verification; then
        log_success "=========================================="
        log_success "DEPLOYMENT COMPLETED SUCCESSFULLY!"
        log_success "=========================================="
        log_success "Branch filtering fixes have been deployed."
        log_success "Backup location: $BACKUP_DIR"
        log_success "Deployment log: $LOG_FILE"
    else
        log_error "Final verification failed. Please check the system."
        exit 1
    fi
}

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  deploy    - Run full deployment"
    echo "  verify    - Run verification only"
    echo "  rollback  - Run emergency rollback"
    echo "  help      - Show this help message"
    echo
    echo "Examples:"
    echo "  $0 deploy    # Deploy branch filtering fixes"
    echo "  $0 verify    # Verify current deployment"
    echo "  $0 rollback  # Emergency rollback"
}

# Main script logic
case "${1:-deploy}" in
    "deploy")
        deploy
        ;;
    "verify")
        log "Running verification only..."
        run_deployment_verification
        ;;
    "rollback")
        log "Running emergency rollback..."
        python3 rollback_branch_filtering.py
        ;;
    "help"|"-h"|"--help")
        show_usage
        ;;
    *)
        log_error "Unknown option: $1"
        show_usage
        exit 1
        ;;
esac