#!/bin/bash

# =============================================================================
# Expertissimo Laravel Deployment Script
# =============================================================================
# This script automates the deployment process:
# 1. Pulls latest code from git
# 2. Increments asset version for cache busting
# 3. Clears Laravel caches
# 4. Updates dependencies if needed
# =============================================================================

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Show help and exit early if requested (before any other operations)
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    echo "Usage: ./deploy.sh [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -c, --composer        Also update Composer dependencies"
    echo "  -n, --npm             Also install NPM deps and build assets"
    echo "  --fix-permissions     Apply file permissions (production/development)"
    echo "  -h, --help            Show this help message"
    echo ""
    echo "Security Features:"
    echo "  • Automatic environment detection (production vs development)"
    echo "  • Secure file permissions for production (775 with setgid)"
    echo "  • Dedicated 'laravel' user for cron tasks in production"
    echo "  • Basic permissions for development environments"
    echo ""
    echo "Examples:"
    echo "  ./deploy.sh                        # Basic deployment (no permissions)"
    echo "  ./deploy.sh --fix-permissions      # Deployment with permissions fix"
    echo "  ./deploy.sh --composer             # With Composer update"
    echo "  ./deploy.sh --npm                  # With NPM build"
    echo "  ./deploy.sh -c -n --fix-permissions # Full deployment with all updates"
    echo ""
    echo "Production Scripts (in deploy/ folder):"
    echo "  • fix-permissions-production.sh - Secure permissions setup"
    echo "  • setup-cron-production.sh     - Secure cron configuration"
    echo "  • DEPLOYMENT-SECURITY.md       - Security documentation"
    exit 0
fi

# Parse command line arguments
UPDATE_COMPOSER=false
UPDATE_NPM=false
FIX_PERMISSIONS=false

for arg in "$@"; do
    case $arg in
        -c|--composer)
            UPDATE_COMPOSER=true
            shift
            ;;
        -n|--npm)
            UPDATE_NPM=true
            shift
            ;;
        --fix-permissions)
            FIX_PERMISSIONS=true
            shift
            ;;
        *)
            # Unknown option
            ;;
    esac
done

# Check if we're in the right directory
if [ ! -f "artisan" ]; then
    print_error "This script must be run from the Laravel project root directory!"
    exit 1
fi

print_status "Starting deployment process..."

# =============================================================================
# 1. Git Operations
# =============================================================================
print_status "Pulling latest changes from git..."

# Check if there are uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
    print_warning "You have uncommitted changes. Proceeding anyway..."
fi

# Get current branch
CURRENT_BRANCH=$(git branch --show-current)
print_status "Current branch: $CURRENT_BRANCH"

# Configure git to use SSH for GitHub if HTTPS is detected
REMOTE_URL=$(git remote get-url origin)
if [[ $REMOTE_URL == https://github.com/* ]]; then
    print_status "Converting HTTPS remote to SSH for deployment..."
    SSH_URL=$(echo $REMOTE_URL | sed 's/https:\/\/github.com\//git@github.com:/')
    git remote set-url origin $SSH_URL
    print_success "Remote URL updated to SSH"
fi

# Pull latest changes
if git pull origin $CURRENT_BRANCH 2>/dev/null; then
    print_success "Git pull completed successfully"
else
    print_warning "Git pull failed - trying to fetch and reset..."
    if git fetch origin $CURRENT_BRANCH && git reset --hard origin/$CURRENT_BRANCH; then
        print_success "Repository updated via fetch/reset"
    else
        print_warning "Git operations failed - continuing with deployment..."
    fi
fi

# =============================================================================
# 2. Version Management
# =============================================================================
print_status "Incrementing asset version..."

# Read current version from .env
CURRENT_VERSION=$(grep "ASSET_VERSION=" .env | cut -d'=' -f2)
print_status "Current version: $CURRENT_VERSION"

# Increment patch version
if [[ $CURRENT_VERSION =~ ^([0-9]+)\.([0-9]+)\.?([0-9]*)$ ]]; then
    MAJOR=${BASH_REMATCH[1]}
    MINOR=${BASH_REMATCH[2]}
    PATCH=${BASH_REMATCH[3]}
    
    # If no patch version, start with 1, otherwise increment
    if [ -z "$PATCH" ]; then
        NEW_VERSION="$MAJOR.$MINOR.1"
    else
        NEW_PATCH=$((PATCH + 1))
        NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
    fi
elif [[ $CURRENT_VERSION =~ ^([0-9]+)\.([0-9]+)$ ]]; then
    # Version format x.y -> x.y.1
    NEW_VERSION="$CURRENT_VERSION.1"
else
    print_error "Invalid version format in .env file: $CURRENT_VERSION"
    exit 1
fi

# Update .env file
if sed -i "s/ASSET_VERSION=$CURRENT_VERSION/ASSET_VERSION=$NEW_VERSION/" .env; then
    print_success "Version updated from $CURRENT_VERSION to $NEW_VERSION"
else
    print_error "Failed to update version in .env file"
    exit 1
fi

# =============================================================================
# 3. Composer Dependencies (Optional)
# =============================================================================
if [ "$1" = "--composer" ] || [ "$1" = "-c" ]; then
    print_status "Updating Composer dependencies..."
    if composer install --no-dev --optimize-autoloader; then
        print_success "Composer dependencies updated"
    else
        print_warning "Composer update failed, continuing anyway..."
    fi
fi

# =============================================================================
# 4. NPM Dependencies (Optional)
# =============================================================================
if [ "$1" = "--npm" ] || [ "$1" = "-n" ]; then
    print_status "Installing NPM dependencies..."
    if npm ci; then
        print_success "NPM dependencies installed"
        
        print_status "Building assets..."
        if npm run production; then
            print_success "Assets built successfully"
        else
            print_warning "Asset build failed, continuing anyway..."
        fi
    else
        print_warning "NPM install failed, continuing anyway..."
    fi
fi

# =============================================================================
# 5. Laravel Cache Management
# =============================================================================
print_status "Clearing Laravel caches..."

# Clear various caches
php artisan config:clear
php artisan view:clear
php artisan route:clear
sudo php artisan cache:clear

# Recreate config cache for production
if [ "$APP_ENV" = "production" ]; then
    print_status "Caching configuration for production..."
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
fi

print_success "Laravel caches cleared"

# =============================================================================
# 6. Generate Initial Sitemaps (if needed)
# =============================================================================
print_status "Checking and generating initial sitemaps..."

# Check if routes-services sitemap exists, if not generate it
if [ ! -f "public/sitemaps/sitemap-routes-services.xml" ]; then
    print_status "Routes-services sitemap not found, generating..."
    if php artisan sitemap:generate-routes-services; then
        print_success "Routes-services sitemap generated successfully"
    else
        print_warning "Failed to generate routes-services sitemap"
    fi
else
    print_status "Routes-services sitemap already exists"
fi

# =============================================================================
# 7. Sitemap Symlink Setup
# =============================================================================
print_status "Setting up sitemap symlink..."

# Create symlink for main sitemap if it doesn't exist or is broken
SITEMAP_LINK="public/sitemap.xml"
SITEMAP_TARGET="sitemaps/sitemap.xml"

if [ ! -L "$SITEMAP_LINK" ] || [ ! -e "$SITEMAP_LINK" ]; then
    # Remove existing file if it's not a symlink
    if [ -f "$SITEMAP_LINK" ] && [ ! -L "$SITEMAP_LINK" ]; then
        rm "$SITEMAP_LINK"
        print_status "Removed existing sitemap file"
    fi
    
    # Create symlink
    if ln -sf "$SITEMAP_TARGET" "$SITEMAP_LINK"; then
        print_success "Created sitemap symlink: $SITEMAP_LINK -> $SITEMAP_TARGET"
    else
        print_warning "Failed to create sitemap symlink"
    fi
else
    print_status "Sitemap symlink already exists and is valid"
fi

# =============================================================================
# 8. File Permissions (Production Security)
# =============================================================================

if [ "$FIX_PERMISSIONS" = true ]; then
    print_status "Applying secure file permissions..."

    # Check if we're in production environment
    IS_PRODUCTION=false
    if [ "$APP_ENV" = "production" ] || grep -q "APP_ENV=production" .env 2>/dev/null; then
        IS_PRODUCTION=true
    fi
if [ "$APP_ENV" = "production" ] || grep -q "APP_ENV=production" .env 2>/dev/null; then
    IS_PRODUCTION=true
fi

if [ "$IS_PRODUCTION" = true ]; then
    print_status "Production environment detected - applying secure permissions..."
    
    # Run the production permissions script
    if [ -f "deploy/fix-permissions-production.sh" ]; then
        if sudo bash deploy/fix-permissions-production.sh; then
            print_success "Secure permissions applied successfully"
        else
            print_warning "Failed to apply secure permissions, continuing with basic permissions..."
            # Fallback to basic permissions
            sudo chmod -R 775 storage || print_warning "Could not set storage permissions"
            sudo chmod -R 775 bootstrap/cache || print_warning "Could not set bootstrap/cache permissions"
        fi
    else
        print_warning "Production permissions script not found, applying basic permissions..."
        chmod -R 775 storage 2>/dev/null || print_warning "Could not set storage permissions"
        chmod -R 775 bootstrap/cache 2>/dev/null || print_warning "Could not set bootstrap/cache permissions"
    fi
    
    # Setup cron if not already configured
    if [ -f "deploy/setup-cron-production.sh" ]; then
        if ! sudo crontab -u laravel -l >/dev/null 2>&1; then
            print_status "Setting up secure cron for Laravel scheduler..."
            if sudo bash deploy/setup-cron-production.sh; then
                print_success "Secure cron configured successfully"
            else
                print_warning "Failed to configure secure cron"
            fi
        else
            print_status "Secure cron already configured"
        fi
    fi
else
    print_status "Development environment - applying basic permissions..."
    # Basic permissions for development
    sudo chmod -R 775 storage || print_warning "Could not set storage permissions (may require sudo)"
    sudo chmod -R 775 bootstrap/cache || print_warning "Could not set bootstrap/cache permissions (may require sudo)"
    sudo chmod -R 775 public/sitemaps || print_warning "Could not set sitemaps permissions (may require sudo)"
fi

    print_success "File permissions updated"
else
    print_status "Skipping file permissions (use --fix-permissions to apply)"
fi

# =============================================================================
# 9. Final Status
# =============================================================================
print_success "🚀 Deployment completed successfully!"
echo ""
print_status "Summary:"
echo "  • Git: Pulled latest changes from $CURRENT_BRANCH"
echo "  • Version: Updated from $CURRENT_VERSION to $NEW_VERSION"
echo "  • Cache: Cleared all Laravel caches"
echo "  • Sitemap: Symlink created/verified (sitemap.xml -> sitemaps/sitemap.xml)"
if [ "$FIX_PERMISSIONS" = true ]; then
    if [ "$IS_PRODUCTION" = true ]; then
        echo "  • Permissions: Applied secure production permissions (user: laravel)"
        echo "  • Security: Production-grade file permissions configured"
    else
        echo "  • Permissions: Applied development permissions"
    fi
else
    echo "  • Permissions: Skipped (use --fix-permissions to apply)"
fi
echo ""
print_status "Your website is now updated with version $NEW_VERSION"
echo ""
