pipeline {
    agent any

    environment {
        APP_NAME = 'Polizia'
        APP_ENV = 'testing'
        APP_KEY = 'base64:1YsMWZ+cIDVa5NIePkjsXVheT9rbykHDs/CnGPUQdqU='
        APP_DEBUG = 'false'
        APP_URL = 'https://frascati.dev.webmagistri.biz'

        LOG_CHANNEL = 'stack'
        LOG_DEPRECATIONS_CHANNEL = 'null'
        LOG_LEVEL = 'debug'

        DB_CONNECTION = 'mysql'
        DB_HOST = '127.0.0.1'
        DB_PORT = '3306'
        DB_DATABASE = 'polizia_online'
        DB_USERNAME = 'admin'
        DB_PASSWORD = 'admin'

        MCTC_URL = 'https://www.ilportaledellautomobilista.it/Info-ws/services'
        MCTC_USER = 'CMRM001301'
        MCTC_PASSWORD = '2PMPM*86'

        STORAGE_PATH = 'app/public/'

        REMOTE_HOST = '10.2.0.10'
        REMOTE_USER = 'fratini'
        REMOTE_DIR = '/var/www/polizia'

        ADMIN_EMAIL = 'f.fratini@webmagistri.it'
    }

    stages {
        stage('Verify Host') {
            steps {
                sh 'hostname'
                sh 'hostname -I'
                sh 'whoami'
            }
        }

        stage('Get Code') {
            steps {
                checkout scm
            }
        }

        stage('Debug Branch Info') {
            steps {
                script {
                    // Store the branch info for later use
                    env.CURRENT_BRANCH = sh(script: 'git rev-parse --abbrev-ref HEAD || echo "HEAD"', returnStdout: true).trim()
                    echo "Current branch detected as: ${env.CURRENT_BRANCH}"
                }
            }
        }

        stage('Deploy to Server') {
            when {
                expression {
                    // Always deploy from develop branch or if we're in a detached HEAD state
                    return env.CURRENT_BRANCH == 'HEAD' || env.CURRENT_BRANCH == 'develop' ||
                           env.GIT_BRANCH == 'origin/develop' || env.BRANCH_NAME == 'develop'
                }
            }
            steps {
                echo "Starting deployment to ${REMOTE_HOST} as user ${REMOTE_USER}"

                sh '''
                    # Make sure SSH directory exists with correct permissions
                    mkdir -p ~/.ssh
                    chmod 700 ~/.ssh

                    # Create remote directory - without using sudo
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "mkdir -p ${REMOTE_DIR}"

                    # Remove existing files (if any) that we have permission to remove
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "find ${REMOTE_DIR} -type f -writable -delete || true"

                    # Create a tar archive excluding unnecessary files
                    tar --exclude='.git' --exclude='node_modules' --exclude='vendor' -czf /tmp/deployment.tar.gz .

                    # Copy the archive to the remote server
                    scp -o StrictHostKeyChecking=no /tmp/deployment.tar.gz ${REMOTE_USER}@${REMOTE_HOST}:/tmp/

                    # Extract the archive on the remote server with --no-same-owner to avoid permission issues
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && tar -xzf /tmp/deployment.tar.gz --no-same-owner || echo 'Tar extraction had some issues, but continuing...'"

                    # Clean up
                    rm -f /tmp/deployment.tar.gz
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "rm -f /tmp/deployment.tar.gz"

                    # Check for PHP
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "php -v || echo 'PHP not available on remote server'"

                    # Check for Composer and install it if missing (without sudo)
                    echo "Checking for Composer..."
                    COMPOSER_INSTALLED=$(ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "command -v composer || echo 'not found'")
                    if [[ "$COMPOSER_INSTALLED" == *"not found"* ]]; then
                        echo "Composer not found. Please install it manually on the remote server."
                    else
                        echo "Composer is already installed."
                    fi

                    # Run Composer install
                    echo "Running composer install..."
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && composer install --no-interaction --no-dev --prefer-dist || echo 'Composer install failed, continuing...'"

                    # Check for Node.js/NPM
                    NODE_INSTALLED=$(ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "command -v node || echo 'not found'")
                    if [[ "$NODE_INSTALLED" == *"not found"* ]]; then
                        echo "Node.js not found - skipping npm steps"
                    else
                        echo "Running npm install and build..."
                        ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && npm install && npm run build || echo 'NPM build failed, continuing...'"
                    fi

                    # Set proper permissions for Laravel directories that need to be writable
                    echo "Setting directory permissions..."
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && mkdir -p bootstrap/cache storage/framework/sessions storage/framework/views storage/framework/cache storage/logs"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && chmod -R 775 storage bootstrap/cache || echo 'Permission setting had some issues, but continuing...'"

                    # Run Laravel artisan commands
                    echo "Running Laravel artisan commands..."
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan migrate --force || echo 'Migration failed, continuing...'"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan config:cache || echo 'Config cache failed, continuing...'"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan route:cache || echo 'Route cache failed, continuing...'"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan view:cache || echo 'View cache failed, continuing...'"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan optimize || echo 'Optimize failed, continuing...'"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan storage:link || echo 'Storage link failed, continuing...'"

                    # Notify completion
                    echo "Deployment completed. Some steps may have been skipped due to permission issues."
                    echo "You may need to manually adjust file permissions or restart services if needed."
                '''
            }
        }
    }

    post {
        always {
            script {
                cleanWs()
            }
        }
        success {
            echo 'Build completed! The Polizia application has been deployed to 10.2.0.10'
            echo 'Note: You may need to manually restart web services and adjust permissions if needed.'

            script {
                mail to: env.ADMIN_EMAIL,
                     subject: 'Polizia - Build Completed',
                     body: 'The build process has completed. The Polizia application has been deployed to the server at 10.2.0.10. You may need to manually restart web services and adjust permissions if needed.'
            }
        }
        failure {
            echo 'Build failed! Please check the console output to fix the issues.'

            script {
                mail to: env.ADMIN_EMAIL,
                     subject: 'Polizia - Build Failed',
                     body: 'The build has failed. Please check Jenkins for details.'
            }
        }
    }
}
