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/html/polizia'

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

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

        stage('Check Dependencies') {
            steps {
                sh 'php --version || echo "PHP not available locally"'
                sh 'composer --version || echo "Composer not available locally"'
                sh 'node --version || echo "Node not available locally"'
                sh 'npm --version || echo "NPM not available locally"'

                // Check for rsync
                sh 'rsync --version || echo "rsync not available, please install it on Jenkins server"'
            }
        }

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

        stage('Debug Branch Info') {
            steps {
                sh 'git branch -v || echo "Could not get branch info"'
                sh 'git status || echo "Could not get status"'
                sh 'echo "BRANCH_NAME: ${BRANCH_NAME:-not set}"'
                sh 'echo "GIT_BRANCH: ${GIT_BRANCH:-not set}"'
                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}"

                // Using SSH key authentication - no password required
                sh '''
                    # Make sure SSH directory exists with correct permissions
                    mkdir -p ~/.ssh
                    chmod 700 ~/.ssh

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

                    # Since rsync isn't available, use scp to copy files
                    # First, create a tar archive
                    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
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "tar -xzf /tmp/deployment.tar.gz -C ${REMOTE_DIR}/"

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

                    # Run composer install
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && composer install --no-interaction --no-dev --prefer-dist"

                    # Run npm install and build
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && npm install && npm run build"

                    # Run Laravel artisan commands
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan migrate --force && php artisan config:cache && php artisan route:cache && php artisan view:cache && php artisan optimize && php artisan storage:link"

                    # Set permissions
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && chmod -R 775 storage bootstrap/cache && sudo chown -R www-data:www-data ."

                    # Restart services
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "sudo systemctl restart php8.1-fpm || sudo systemctl restart php-fpm || echo 'PHP service restart failed, may need manual intervention'"
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "sudo systemctl restart nginx || echo 'Nginx restart failed, may need manual intervention'"

                    # Clear cache
                    ssh -o StrictHostKeyChecking=no ${REMOTE_USER}@${REMOTE_HOST} "cd ${REMOTE_DIR} && php artisan cache:clear"
                '''
            }
        }
    }

    post {
        always {
            script {
                cleanWs()
            }
        }
        success {
            echo 'Build successful! The Polizia application is now deployed to 10.2.0.10'

            script {
                mail to: env.ADMIN_EMAIL,
                     subject: 'Polizia - Build Successful',
                     body: 'The build was successful and the Polizia application has been deployed to the server at 10.2.0.10'
            }
        }
        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.'
            }
        }
    }
}
