pipeline {
    agent {
        node {
            label 'jenkins-slave'
        }
    }
    options {
        // Deshabilita ejecuciones concurrentes
        disableConcurrentBuilds()
    }
    environment {
        ESXI_PASS = credentials('VI_PASSWORD')
        QINDEL_PASS = credentials('jenkins-user-slave-password')
        PATH = "/home/qindel/bin/ovftool:${env.PATH}"
    }
    stages {
        stage('Prepare environment') {
            steps {
                dir ('tests/API-dhcp') {
                    echo "Install vagrant plugin"
                    sh '''
                    if ! vagrant plugin list | grep -q vagrant-vmware-esxi; then
                        echo "Vagrant plugin vagrant-vmware-esxi not found. Installing..."
                        vagrant plugin install vagrant-vmware-esxi
                    else
                        echo "Vagrant plugin vagrant-vmware-esxi is already installed."
                    fi
                    '''
                    echo "Deploy API server for DHCP with Vagrant"
                    sh 'vagrant up --provider=vmware_esxi --provision'
                }
            }
        }
        stage('Check Installation') {
            steps {
                dir ('tests/API-dhcp') {
                    echo "Get IP of API server for DHCP with Vagrant"
                    sh '''
                        set -e 
                        new_ip=$(vagrant ssh -c "hostname -I" | tr -d '\r') 
                        echo "$QINDEL_PASS" | sudo -S bash -c "echo '$new_ip api-test' >> /etc/hosts"
                        echo "IP: $new_ip"
                        curl -f -L -X 'GET' -H 'accept: application/json' "http://api-test/opengnsys3/rest/dhcp/subnets/"
                    '''
                }
            }
        }
        stage('Run API tests') {
            steps {
                echo 'Running API tests'
                // Aquí incluirías los comandos para ejecutar tus pruebas
            }
        }
    }
    post {
        success {
            // Si el trabajo ha sido exitoso, destruir la máquina de Vagrant
            echo "El trabajo ha finalizado con éxito. Destruyendo máquina Vagrant..."
            dir ('tests/API-dhcp') {
                sh 'vagrant destroy -f'
            }
        }
        always {
            script {
                def userCause = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause)
                
                if (userCause != null) {
                    // Si fue lanzado manualmente, obtener el usuario y su correo desde las propiedades de Jenkins
                    def userId = userCause.getUserId()
                    def userEmail = getUserEmail(userId)
                    
                    if (userEmail) {
                        echo "El correo del usuario que lanzó el build manualmente es: ${userEmail}"
                        
                        // Enviar correo al usuario que lanzó el build manualmente
                        mail to: "${userEmail}",
                             subject: "Jenkins Job Completed (Manual): ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                             body: """
                                El job '${env.JOB_NAME}' con número de build ${env.BUILD_NUMBER} ha finalizado (ejecutado manualmente).
                                
                                Estado: ${currentBuild.currentResult}
                                
                                Revisa los detalles del build en: ${env.BUILD_URL}
                             """
                    } else {
                        echo "No se pudo encontrar un correo electrónico para el usuario: ${userId}"
                    }
                } else {
                    // Si fue lanzado automáticamente, obtener el correo del committer
                    def committerEmail = sh(
                        script: 'git log -1 --pretty=format:"%ae"',
                        returnStdout: true
                    ).trim()
                    
                    echo "El build fue lanzado automáticamente. Correo del committer: ${committerEmail}"
                    
                    // Enviar correo al committer
                    mail to: "${committerEmail}",
                         subject: "Jenkins Job Completed (Automático): ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                         body: """
                            El job '${env.JOB_NAME}' con número de build ${env.BUILD_NUMBER} ha finalizado (ejecutado automáticamente).
                            
                            Estado: ${currentBuild.currentResult}
                            
                            Revisa los detalles del build en: ${env.BUILD_URL}
                         """
                }
            }
        }
    }
}

@NonCPS
def getUserEmail(userId) {
    def jenkinsInstance = jenkins.model.Jenkins.getInstanceOrNull()
    if (jenkinsInstance != null) {
        def user = jenkinsInstance.getUser(userId)
        return user.getProperty(jenkins.plugins.mailer.tasks.Mailer.UserProperty)?.getAddress()
    }
    return null
}
