pipeline {
    agent {
            label 'jenkins-slave'
    }

    environment {
        DOCKER_REPO = "opengnsys"
        DOCKER_TAG = "${env.BUILD_NUMBER}"
        DOCKER_IMAGE_NAME = "ogcore"
        BRANCH_NAME = "${env.BRANCH_NAME}"
        DOCKER_IDENTITY = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}-php:${BRANCH_NAME}-${DOCKER_TAG}"
        DOCKER_IDENTITY_NGINX = "${DOCKER_REPO}/${DOCKER_IMAGE_NAME}-nginx:${BRANCH_NAME}-${DOCKER_TAG}"
        DOCKER_COMPOSE_TEMPLATE = 'docker-compose-ci-template.yaml'
        DOCKER_COMPOSE_FILE = 'docker-compose-ci-tmp.yaml'
    }

    stages {
        stage ("Checkout") {
            steps {
                checkout scm
            }
        }
        stage('Build Environment') {
            steps {
                sh '''
                # Detener todos los contenedores si hay alguno ejecutándose
                if [ $(docker ps -q | wc -l) -gt 0 ]; then
                    docker stop $(docker ps -q)
                fi
        
                # Eliminar todos los contenedores si hay alguno detenido
                if [ $(docker ps -a -q | wc -l) -gt 0 ]; then
                    docker rm $(docker ps -a -q)
                fi
                '''
                script {

                    docker.build("${DOCKER_IDENTITY}", '-f docker/Dockerfile-jenkins-php .')
                    docker.build("${DOCKER_IDENTITY_NGINX}", '-f docker/Dockerfile-nginx .')
                }
            }
        }
        stage(('Prepare Docker Composer')) {
            steps {
                sh """
                sed 's|ogcore-php:static|${DOCKER_IDENTITY}|g; s|ogcore-nginx:static|${DOCKER_IDENTITY_NGINX}|g' ${DOCKER_COMPOSE_TEMPLATE} > ${DOCKER_COMPOSE_FILE}
                cat ${DOCKER_COMPOSE_FILE}
                """
            }
        }
        stage('Run containers') {
            steps { 
                sh "docker compose -f ${DOCKER_COMPOSE_FILE} up -d"
            }
        }
        stage('Install dependencies') {
            steps {
                // Install dependencies
                sh """
                docker compose exec php mkdir -p /report
                docker compose exec php composer install
                docker compose exec php php bin/console lexik:jwt:generate-keypair --overwrite
                docker compose exec php php bin/console doctrine:migrations:migrate --no-interaction
                docker compose exec php php bin/console doctrine:fixtures:load --no-interaction
                """
            }
        }
        stage('Tests') {
            steps {
                // Run tests
                sh """
                docker compose exec php bin/phpunit --log-junit /report/phpunit.xml
                """
            }
        }
        stage ("Publish Image") {
            steps {
                script {
                    docker.withRegistry('https://index.docker.io/v1/', 'docker-hub-credentials') {
                        docker.image("${DOCKER_IDENTITY}").push()
                        docker.image("${DOCKER_IDENTITY_NGINX}").push()
                        if (env.BRANCH_NAME == 'main') {
                            docker.image("${DOCKER_IDENTITY}").push("latest")
                            docker.image("${DOCKER_IDENTITY_NGINX}").push("latest")
                        }
                        if (env.TAG_NAME) {
                            docker.image("${DOCKER_IDENTITY}").push("${env.TAG_NAME}")
                            docker.image("${DOCKER_IDENTITY_NGINX}").push("${env.TAG_NAME}")
                        }
                    }
                }
            }
        }

    }
    post {
        always {    
            script {
                def committerEmail = sh (
                    script: "git show -s --pretty=%ae",
                    returnStdout: true
                ).trim()
                def buildResult = currentBuild.currentResult
                mail to: committerEmail, 
                subject: "Opengnsys CI Build ${env.JOB_NAME} - ${env.BRANCH_NAME} - ${buildResult}", 
                body: """
                <h1>Opengnsys CI Build ${JOB_NAME} - ${BRANCH_NAME} - ${buildResult}</h1>
                <p>Build Number: ${BUILD_NUMBER}</p>
                <p>Build URL: ${BUILD_URL}</p>º

                Saludos cordiales,
                Opengnsys CI
                """
            }
            sh "docker compose -f ${DOCKER_COMPOSE_FILE} cp php:/report/phpunit.xml phpunit.xml"
            // Publish JUnit test results
            xunit (
                thresholds: [ skipped(failureThreshold: '0') , failed(failureThreshold: '0') ], 
                tools: [ PHPUnit(pattern: 'phpunit.xml') ]
            )
            // Remove containers
            sh "docker compose -f ${DOCKER_COMPOSE_FILE} down"
            sh "docker compose -f ${DOCKER_COMPOSE_FILE} rm -f"
            sh "docker rmi ${DOCKER_IDENTITY}"
            sh "docker rmi ${DOCKER_IDENTITY_NGINX}"
        }
    }
}
