@Library('cadoles') _

pipeline {
    agent {
        dockerfile {
            label 'docker'
            filename 'Dockerfile'
            dir 'misc/jenkins'
            args '-v /var/run/docker.sock:/var/run/docker.sock --network host'
        }
    }

    stages {
        stage('Cancel older jobs') {
            steps {
                script {
                    def buildNumber = env.BUILD_NUMBER as int
                    if (buildNumber > 1) milestone(buildNumber - 1)
                    milestone(buildNumber)
                }
            }
        }

        stage('Run unit tests') {
            steps {
                script {
                    sh 'make test'
                }
            }
        }

        stage('Release binaries and packages') {
            when {
                anyOf {
                    branch 'master'
                    branch 'develop'
                }
            }
            steps {
                script {
                    withCredentials([
                        usernamePassword([
                            credentialsId: 'forge-jenkins',
                            usernameVariable: 'GITEA_RELEASE_USERNAME',
                            passwordVariable: 'GITEA_RELEASE_PASSWORD'
                        ])
                    ]) {
                        sh 'make gitea-release'
                    }
                }
            }
        }

        stage('Build and release Docker image') {
            when {
                anyOf {
                    branch 'master'
                    branch 'develop'
                }
            }
            steps {
                script {
                    withCredentials([
                        usernamePassword([
                            credentialsId: 'kipp-credentials',
                            usernameVariable: 'DOCKER_REGISTRY_USERNAME',
                            passwordVariable: 'DOCKER_REGISTRY_PASSWORD'
                        ])
                    ]) {
                        sh """
                        echo '${env.DOCKER_REGISTRY_PASSWORD}' | docker login --username '${env.DOCKER_REGISTRY_USERNAME}' --password-stdin reg.cadoles.com
                        make docker-build docker-release
                        """
                    }
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}