@Library('jenkins-shared-library') _
pipeline {
    agent {
        label 'jenkins-slave'
    }
    environment {
        DEBIAN_FRONTEND = 'noninteractive'
        DEFAULT_DEV_NAME = 'Opengnsys Team'
        DEFAULT_DEV_EMAIL = 'opengnsys@qindel.com'
    }
    options {
        skipDefaultCheckout()
    }
    parameters {
        string(name: 'DEV_NAME', defaultValue: '', description: 'Nombre del desarrollador')
        string(name: 'DEV_EMAIL', defaultValue: '', description: 'Email del desarrollador')
    }
    stages {
        stage('Prepare Workspace') {
            steps {
                script {
                    env.BUILD_DIR = "${WORKSPACE}/ogdhcp"
                    sh "mkdir -p ${env.BUILD_DIR}"
                }
            }
        }

        stage('Checkout') {
            steps {
                dir("${env.BUILD_DIR}") {
                    checkout scm
                }
            }
        }

        stage('Generate Changelog') {
            when {
                expression {
                    return env.TAG_NAME != null
                }
            }
            steps {
                script {
                    def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
                    def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL

                    generateDebianChangelog(env.BUILD_DIR, devName, devEmail)
                }
            }
        }

        stage('Build') {
            steps {
                dir("${env.BUILD_DIR}") {
                    sh '''
                    dpkg-buildpackage -us -uc
                    mkdir -p ../artifacts && mv ../*.deb ../*.changes ../*.buildinfo ../artifacts/
                    ssh aptly@172.17.8.68 "rm -rf /var/tmp/opengnsys/debian-repo/ogdhcp && mkdir -p /var/tmp/opengnsys/debian-repo/ogdhcp"
                    scp -r ../artifacts/* aptly@172.17.8.68:/var/tmp/opengnsys/debian-repo/ogdhcp
                    '''
                }
            }    
        }
        stage ('Publish to Debian Repository') {
            when {
                expression {
                    return env.TAG_NAME != null
                }
            }
            agent { label 'debian-repo' }
            steps {
                sh "aptly repo add opengnsys-devel /var/tmp/opengnsys/debian-repo/ogdhcp/*.deb"
            }
        }
    }
    post {
        always {
            notifyBuildStatus('narenas@qindel.com')
        }
    }
}
// stage ('Publish to Debian Repository') {
//     agent { label 'debian-repo' }
//     steps {
//         sh "aptly repo add opengnsys-devel /var/tmp/opengnsys/debian-repo/*.deb"
//     }
// }

