// MouseSoft Draw.io Export jenkins declarative pipeline

pipeline {
    agent { label 'go' }
    options {
        ansiColor('css')
        timestamps()
        buildDiscarder(logRotator(numToKeepStr: '10'))
        skipDefaultCheckout()
        timeout(time: 8, unit: 'MINUTES', activity: true)
    }
    environment {
        PROJECT_OWNER = 'ms'
        PROJECT_ID = 'drawio-export'
        PROJECT_NAME = 'MouseSoft Draw.IO Export'
        ROCKET_TITLE = "${currentBuild.fullDisplayName} (<${env.BUILD_URL}|Open>)"
        RELEASE_ID = 0
    }
    stages {
        stage('Build') {
            parallel {
                stage('Build Linux') {
                    steps {
                        echo "***** BUILD ${PROJECT_NAME} on Linux *****"
                        msSendRocketChat("${ROCKET_TITLE}", msBuildInfo(currentBuild), 'black')
                        cleanWs(disableDeferredWipeout: true, deleteDirs: true)
                        checkout scm
                        sh '''#!/bin/bash
                        make clean vendor lint build dist doc
                        '''
                    }
                }
                stage('Build Windows') {
                    agent{ label 'windows' }
                    environment {
                        GO_OPT = ' '
                        CGO_ENABLED = 0
                    }
                    steps {
                        echo "***** BUILD ${PROJECT_NAME} on Windows *****"
                        cleanWs(disableDeferredWipeout: true, deleteDirs: true)
                        catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
                            checkout scm
                            bat 'make clean vendor build dist'
                        }
                    }
                    post {
                        always {
                            script {
                                if (getContext(hudson.FilePath)) {
                                    archiveArtifacts (
                                        artifacts: 'out/*.zip,out/*.msi',
                                        allowEmptyArchive: true,
                                        fingerprint: true,
                                        onlyIfSuccessful: true,
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
        stage('Test') {
            environment {
                EXPORT_RESULT = true
                COVERAGE_FORMAT = 'xml'
            }
            steps {
                echo "===== TEST ${PROJECT_NAME} ====="
                sh '''#!/bin/bash
                make test coverage
                '''
            }
        }
        stage('Doc') {
            when { anyOf {
                branch 'main'
                branch 'develop'
                branch 'release/*'
                branch 'support/*'
                tag 'v*'
            } }
            environment {
                DOC_FORMAT = 'pdf'
            }
            steps {
                echo "===== MAKE ${PROJECT_NAME} Documentation ====="
                sh '''#!/bin/bash
                make doc
                '''
            }
        }
        stage('Draft Release') {
            when { tag 'v*' }
            steps {
                script {
                    def version = "${TAG_NAME}".substring(1)
                    RELEASE_ID = msCreateRelease(
                        "${PROJECT_OWNER}",
                        "${PROJECT_ID}",
                        "${TAG_NAME}",
                        "${PROJECT_NAME}",
                    )
                }
            }
        }
        stage('Release') {
            parallel {
                stage('Release Linux') {
                    when { tag 'v*' }
                    environment {
                        OUTDIR = 'dist'
                        DIST_TAG = 'empty'
                        GO_LDFLAGS = '-w'
                        GO_OPT = ' '
                    }
                    steps {
                        echo "***** RELEASE ${PROJECT_NAME} for Linux *****"
                        sh '''#!/bin/bash
                        make build package
                        find -O1 dist/ -name '*.changes' -exec dput mousesoft \\{\\} \\;
                        '''
                        script {
                            msUploadFilesToRelease(
                                "${PROJECT_OWNER}",
                                "${PROJECT_ID}",
                                RELEASE_ID,
                                ['dist/*.deb'],
                            )
                            if( currentBuild.currentResult == 'SUCCESS' ) {
                                currentBuild.keepLog = true
                            }
                        }
                        msSendRocketChat("${ROCKET_TITLE}", "Released assets for Linux", 'blue')
                    }
                }
                stage('Release Windows') {
                    agent{ label 'windows' }
                    when { tag 'v*' }
                    environment {
                        OUTDIR = 'dist'
                        DIST_TAG = 'empty'
                        GO_LDFLAGS = '-w'
                        GO_OPT = ' '
                    }
                    steps {
                        echo "***** RELEASE ${PROJECT_NAME} for Windows *****"
                        bat 'make build package'
                        script {
                            msUploadFilesToRelease(
                                "${PROJECT_OWNER}",
                                "${PROJECT_ID}",
                                RELEASE_ID,
                                ['dist/*.msi'],
                            )
                            if( currentBuild.currentResult == 'SUCCESS' ) {
                                currentBuild.keepLog = true
                            }
                        }
                        msSendRocketChat("${ROCKET_TITLE}", "Released assets for Windows", 'blue')
                    }
                    post {
                        success {
                            archiveArtifacts (
                                artifacts: 'dist/*.msi',
                                allowEmptyArchive: false,
                                fingerprint: true,
                            )
                        }
                    }
                }
            }
        }
    }

    post {
        always {
            script {
                if (getContext(hudson.FilePath)) {
                    junit (
                        testResults: 'out/junit-report.xml',
                        allowEmptyResults: true,
                        skipPublishingChecks: true,
                    )
                    cobertura (
                        coberturaReportFile: 'out/coverage.xml',
                        failNoReports: false,
                    )
                    archiveArtifacts (
                        artifacts: 'out/*.tar.*,out/*.zip',
                        allowEmptyArchive: false,
                        fingerprint: true,
                        onlyIfSuccessful: true,
                    )
                    archiveArtifacts (
                        artifacts: 'out/doc/*.pdf',
                        allowEmptyArchive: true,
                        fingerprint: true,
                        onlyIfSuccessful: true,
                    )
                    if (currentBuild.result == 'SUCCESS') {
                        publishHTML(target: [
                            allowMissing: true,
                            alwaysLinkToLastBuild: true,
                            keepAll: false,
                            reportDir: 'out/doc/html',
                            reportFiles: 'index.html',
                            reportTitles: 'Техническая документация',
                            reportName: 'Documentation',
                        ])
                    }
                }
                if( currentBuild.result != 'SUCCESS' ) {
                    currentBuild.keepLog = false
                }
                def timeSec = currentBuild.duration / 1000
                msSendRocketChat(
                    "${ROCKET_TITLE}",
                    "Build ${currentBuild.result} after ${timeSec} sec",
                    msBuildResultColor(),
                )
            }
        }
    }
}
