#!/bin/bash

# ISP Management System - Production Deployment Script
# This script handles proper Laravel deployment to production

set -e  # Exit on any error

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

# Configuration
PROJECT_NAME="ISP Management System"
BACKUP_DIR="backups"
LOG_FILE="deployment.log"

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

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

# Check if running as correct user
check_user() {
    log "Checking user permissions..."
    if [[ $EUID -eq 0 ]]; then
        error "This script should not be run as root"
    fi
    success "User check passed"
}

# Check PHP version
check_php() {
    log "Checking PHP version..."
    PHP_VERSION=$(php -v | head -n 1 | cut -d " " -f 2 | cut -d "." -f 1,2)
    if [[ $(echo "$PHP_VERSION >= 8.1" | bc) -eq 1 ]]; then
        success "PHP version $PHP_VERSION is compatible"
    else
        error "PHP version $PHP_VERSION is not compatible. Requires PHP 8.1+"
    fi
}

# Check required extensions
check_extensions() {
    log "Checking required PHP extensions..."
    REQUIRED_EXTENSIONS=("pdo" "pdo_mysql" "mbstring" "openssl" "tokenizer" "xml" "ctype" "json" "bcmath" "zip")
    
    for ext in "${REQUIRED_EXTENSIONS[@]}"; do
        if php -m | grep -q "^$ext$"; then
            success "Extension $ext is installed"
        else
            error "Required extension $ext is not installed"
        fi
    done
}

# Create backup
create_backup() {
    log "Creating backup..."
    
    # Create backup directory
    mkdir -p $BACKUP_DIR
    
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    BACKUP_NAME="backup_$TIMESTAMP"
    
    # Backup database
    if [ -f .env ]; then
        DB_HOST=$(grep DB_HOST .env | cut -d '=' -f2)
        DB_DATABASE=$(grep DB_DATABASE .env | cut -d '=' -f2)
        DB_USERNAME=$(grep DB_USERNAME .env | cut -d '=' -f2)
        DB_PASSWORD=$(grep DB_PASSWORD .env | cut -d '=' -f2)
        
        log "Backing up database..."
        mysqldump -h$DB_HOST -u$DB_USERNAME -p$DB_PASSWORD $DB_DATABASE > $BACKUP_DIR/database_$BACKUP_NAME.sql
        success "Database backup created: $BACKUP_DIR/database_$BACKUP_NAME.sql"
    fi
    
    # Backup .env file
    if [ -f .env ]; then
        cp .env $BACKUP_DIR/env_$BACKUP_NAME
        success "Environment file backed up: $BACKUP_DIR/env_$BACKUP_NAME"
    fi
    
    # Backup storage directory
    if [ -d storage ]; then
        tar -czf $BACKUP_DIR/storage_$BACKUP_NAME.tar.gz storage/
        success "Storage directory backed up: $BACKUP_DIR/storage_$BACKUP_NAME.tar.gz"
    fi
}

# Install/Update Composer dependencies
install_dependencies() {
    log "Installing Composer dependencies..."
    
    if [ ! -f composer.json ]; then
        error "composer.json not found"
    fi
    
    # Install dependencies
    composer install --optimize-autoloader --no-dev --no-interaction
    success "Composer dependencies installed"
}

# Setup environment
setup_environment() {
    log "Setting up environment..."
    
    # Copy environment file if not exists
    if [ ! -f .env ]; then
        if [ -f env.example ]; then
            cp env.example .env
            warning ".env file created from env.example"
        else
            error ".env file not found and no env.example available"
        fi
    fi
    
    # Generate APP_KEY if not set
    if ! grep -q "APP_KEY=base64:" .env; then
        log "Generating application key..."
        php artisan key:generate --force
        success "Application key generated"
    fi
    
    success "Environment setup completed"
}

# Run database migrations
run_migrations() {
    log "Running database migrations..."
    
    # Check database connection
    if ! php artisan migrate:status > /dev/null 2>&1; then
        error "Cannot connect to database. Please check your database configuration."
    fi
    
    # Run migrations
    php artisan migrate --force
    success "Database migrations completed"
}

# Optimize application
optimize_application() {
    log "Optimizing application..."
    
    # Clear all caches
    php artisan config:clear
    php artisan route:clear
    php artisan view:clear
    php artisan cache:clear
    
    # Cache configurations for production
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    
    success "Application optimization completed"
}

# Set proper permissions
set_permissions() {
    log "Setting proper file permissions..."
    
    # Set directory permissions
    find . -type d -exec chmod 755 {} \;
    
    # Set file permissions
    find . -type f -exec chmod 644 {} \;
    
    # Set executable permissions for scripts
    chmod +x artisan
    chmod +x scripts/*.sh
    
    # Set writable permissions for Laravel directories
    chmod -R 775 storage/
    chmod -R 775 bootstrap/cache/
    
    success "File permissions set"
}

# Verify deployment
verify_deployment() {
    log "Verifying deployment..."
    
    # Check if application is accessible
    if php artisan --version > /dev/null 2>&1; then
        success "Laravel application is accessible"
    else
        error "Laravel application is not accessible"
    fi
    
    # Check database connection
    if php artisan migrate:status > /dev/null 2>&1; then
        success "Database connection is working"
    else
        error "Database connection failed"
    fi
    
    # Check if key is set
    if grep -q "APP_KEY=base64:" .env; then
        success "Application key is properly set"
    else
        error "Application key is not set"
    fi
    
    success "Deployment verification completed"
}

# Main deployment process
main() {
    log "Starting deployment of $PROJECT_NAME"
    log "=========================================="
    
    check_user
    check_php
    check_extensions
    create_backup
    install_dependencies
    setup_environment
    run_migrations
    optimize_application
    set_permissions
    verify_deployment
    
    success "=========================================="
    success "Deployment completed successfully!"
    success "Backup files are stored in: $BACKUP_DIR"
    success "Deployment log: $LOG_FILE"
    
    log "Next steps:"
    log "1. Test the application functionality"
    log "2. Monitor error logs: tail -f storage/logs/laravel.log"
    log "3. Check application status: php artisan about"
}

# Run main function
main "$@" 