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'
                    echo 'Create Python venv to work with robotframework'
                    sh '''
                        python3 -m venv robotframework
                        . robotframework/bin/activate
                        pip install -r requirements.txt
                    '''

                }
            }
        }
        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\n' | sed 's/^[^0-9]*//' | sed 's/[[:space:]]*$//')
                        echo $new_ip > ip.txt
                        echo "$QINDEL_PASS" | sudo -S bash -c "echo '$new_ip api-test' >> /etc/hosts"
                        echo "IP: $new_ip"
                        curl -X 'GET' "http://$new_ip/ogdhcp/v1/subnets" -H 'accept: /'
                    '''
                    script {
                        def new_ip = readFile('ip.txt').trim()
                        env.NEW_IP = new_ip
                    }
                }
            }
        }
        stage('Run API tests') {
            steps {
                dir ('tests/API-dhcp') {

                    echo 'Running API tests'

                    sh '''
                        . robotframework/bin/activate
                        robot --variable BASE_URL:http://${NEW_IP}/ogdhcp/v1 -d results/ robot/
                    '''
                }
                // 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 {
            // Recoger los resultados de los tests
             dir ('tests/API-dhcp') {
                robot outputPath: 'results', 
                      outputFileName: 'output.xml', 
                      logFileName: 'log.html', 
                      reportFileName: 'report.html', 
                      passThreshold: 100.0,
                      unstableThreshold: 75.0
            }
            // Siempre se ejecutará, independientemente del resultado
            script {
                // Elimina la entrada del /etc/hosts
                sh "echo '$QINDEL_PASS' | sudo -S sed -i '/api-test/d' /etc/hosts"
                def recipientEmail = env.BUILD_USER_EMAIL ?: getCommitterEmail()

                mail to: recipientEmail,
                    subject: "Jenkins Job Completed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                    body: """
                        El job '${env.JOB_NAME}' con número de build ${env.BUILD_NUMBER} ha finalizado.
                        
                        Estado: ${currentBuild.currentResult}
                        
                        Revisa los detalles del build en: ${env.BUILD_URL}
                     """
            }
        }
    }
}

def getCommitterEmail() {
    return sh(
        script: 'git log -1 --pretty=format:"%ae"',
        returnStdout: true
    ).trim()
}
