// SPDX-FileCopyrightText: 2023 Vector Informatik GmbH
//
// SPDX-License-Identifier: MIT

// vim: set ft=groovy:

//#################
// Global Variables
//#################

// pipeline config
projectName="vib-main"
artifactName='SilKit'
keepNumBuilds=10 //number of log files on Jenkins, workspaces are always cleaned
publishToArtifactory=false
globalBuildDebugBin=false //debug binaries are only build when doing a release to customers
buildWarningsAsErrors=true // compiler warnings are treated as errors
// artifactory for archiving / packaging
artifactoryServer = Artifactory.server('IntegrationBusArtifactory')
artifactoryBuildInfo = Artifactory.newBuildInfo()

def gitBranch="main-mirror" // overriden in parallel pipeline based on scm vars

def buildConfigs = [
    // Windows builds:
    [

        Name: "VS2017-Win64",
        NodeLabel: "ninja && buildtools2019",
        Arch:"x64",
        MsvcVersion:"14.1",
        PublishArtifacts: true,
        BuildDocs: true,
        CmakePreset: "vs141-x64-release",
    ]
    ,[
        Name: "VS2017-Win32",
        NodeLabel: "ninja && buildtools2019",
        Arch:"x64_x86",
        MsvcVersion:"14.1",
        PublishArtifacts: true,
        BuildDocs: true,
        CmakePreset: "vs141-x86-release",
    ]

    // Linux builds:
    ,[
        Name: "Ubuntu-18.04-clang",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=18.04",
        PublishArtifacts: false,
        CmakePreset: "clang10-release",
    ]
    ,[
        Name: "Ubuntu-18.04-gcc",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=18.04",
        PublishArtifacts: true,
        BuildDocs: true,
        CmakePreset: "gcc8-release",
        TriggerAbiCheck: true,
    ]
    ,[
        Name: "Ubuntu-20.04-gcc-10",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=20.04",
        PublishArtifacts: false,
        CmakePreset: "gcc10-release",
    ]
    ,[
        Name: "Ubuntu-20.04-clang-12",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=20.04",
        PublishArtifacts: false,
        CmakePreset: "clang12-release",
    ]
    ,[
        Name: "Ubuntu-22.04-gcc-12",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=22.04",
        PublishArtifacts: false,
        CmakePreset: "gcc12-release",
    ]
    ,[
        Name: "Ubuntu-22.04-clang-14",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=22.04",
        PublishArtifacts: false,
        CmakePreset: "clang14-release",
        checkLicenses: true,
    ]
    // Sanitizer builds:
    ,[
        Name: "Ubuntu-22.04-clang-14-thread-sanitizer",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=22.04",
        PublishArtifacts: false,
        CmakeArgs: "-D SILKIT_ENABLE_THREADSAN=ON -D SILKIT_BUILD_DASHBOARD=OFF",
        CmakePreset: "clang14-release",
        TestDebug: true,
    ]
    ,[
        Name: "Ubuntu-22.04-clang-14-address-sanitizer",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=22.04",
        PublishArtifacts: false,
        CmakeArgs: "-D SILKIT_ENABLE_ASAN=ON -D SILKIT_BUILD_DASHBOARD=OFF",
        CmakePreset: "clang14-release",
        TestDebug: true,
    ]
    ,[
        Name: "Ubuntu-22.04-clang-14-undefined-behavior-sanitizer",
        NodeLabel: "docker && linux",
        DockerImage: "silkit-ubuntu",
        DockerBuildArgs: "--build-arg UBUNTU_VERSION=22.04",
        PublishArtifacts: false,
        CmakeArgs: "-D SILKIT_ENABLE_UBSAN=ON -D SILKIT_BUILD_DASHBOARD=OFF",
        CmakePreset: "clang14-release",
        TestDebug: true,
    ]
]


//##########################################
// Utilities
//##########################################
@NonCPS
def isFullBuildRequired(branchName) {
    // Master and Pull Requests are always full builds
    if(branchName == 'main-mirror' || branchName.startsWith("PR-")) {
        return true;
    }
    // A user requests a fullbuild by adding a "-full" suffix
    if(branchName.contains("-full")) {
        return true;
    }
    return false
}

@NonCPS
def isDockerNode(label) {
    return label.toUpperCase().contains('DOCKER')
}

@NonCPS
def isClangBuild(label) {
    return label.toUpperCase().contains('CLANG')
}

def setBuildRetention(bi) {
    if(gitBranch == 'main-mirror' || gitBranch == 'origin/main-mirror') {
        bi.retention(maxBuilds: 40, deleteBuildArtifacts: true, async: true)
    } else {
        bi.retention(maxBuilds: 2, maxDays: 50, deleteBuildArtifacts: true, async: true)
    }
}

//recursive submodule git checkout 
def checkoutGit() {
    return checkout([$class: 'GitSCM',
            branches: scm.branches,
            doGenerateSubmoduleConfigurations: false,
            extensions: [
                [$class: 'SubmoduleOption',
                    disableSubmodules: false,
                    parentCredentials: false,
                    recursiveSubmodules: true,
                    reference: '',
                    trackingSubmodules: false]],
            submoduleCfg: [],
            userRemoteConfigs: scm.userRemoteConfigs
        ])
}
def shallowCheckoutGit() {
    return checkout([$class: 'GitSCM',
            branches: scm.branches,
            doGenerateSubmoduleConfigurations: false,
            userRemoteConfigs: scm.userRemoteConfigs
        ])
}

def archiveToArtifactory(pattern) {
    if (! publishToArtifactory ) {
        print("INFO: skipping publishing to artifactory because of user request")
        return
    }

    configFileProvider(
        [configFile(fileId: 'SILKIT_ARTIFACTORY_REPO', variable: 'SILKIT_ARTIFACTORY_REPO')]) {
        def repo = readFile(file: SILKIT_ARTIFACTORY_REPO).trim()
        print("Artifactory: archiving with regexp file spec pattern=${pattern}")
        spec = """{
            "files": [{
                "pattern": "${pattern}",
                "regexp" : "true",
                "target" : "${repo}/${projectName}/${env.GIT_BRANCH}/${env.GIT_COMMIT}/",
                "props"  : "git_commit=${env.GIT_COMMIT};git_branch=${env.GIT_BRANCH};git_url=${env.GIT_URL}"
        }]}"""
        print("artifactory spec=${spec}")
        def buildInfo = artifactoryServer.upload(
            spec: spec,
            failNoOp: true
        )
        setBuildRetention(buildInfo)
        artifactoryBuildInfo.append(buildInfo)
    }
}

def buildDocker(config) {
    stage("Building Docker Image") {
        def dockerImage = config["DockerImage"]
        def dockerDir = "./SilKit/ci/docker"
        def buildArgs = "--build-arg ARTIFACTORY=${artifactoryServer.url} "

        configFileProvider([
            configFile(fileId: 'VECTOR_DOCKER_REGISTRY', variable: 'VECTOR_DOCKER_REGISTRY'),
            configFile(fileId: 'SILKIT_ARTIFACTORY_REPO', variable: 'SILKIT_ARTIFACTORY_REPO'),
            configFile(fileId: 'PROXY_DOMAIN', variable: 'PROXY_DOMAIN'),
            configFile(fileId: 'PYPI_MIRROR', variable: 'PYPI_MIRROR'),
            ]) {
            def registry = readFile(file: VECTOR_DOCKER_REGISTRY).trim()
            buildArgs += " --build-arg REGISTRY=${registry} "

            def repo = readFile(file: SILKIT_ARTIFACTORY_REPO).trim()
            buildArgs += " --build-arg SILKIT_ARTIFACTORY_REPO=${repo} "

            def proxyDomain = readFile(file: PROXY_DOMAIN).trim()
            buildArgs += " --build-arg PROXY_DOMAIN=${proxyDomain} "

            def pypiMirror = readFile(file: PYPI_MIRROR).trim()
            buildArgs += " --build-arg PYPI_MIRROR=${pypiMirror} "

            print("Building docker image ${dockerImage}")
            if(config.containsKey("DockerBuildArgs")) {
                buildArgs += config["DockerBuildArgs"]
            }
            // We assume the docker file (located in the docker subfolder) is named exactly like the docker image
            buildArgs += " -f ${dockerDir}/${dockerImage} ${dockerDir}"
            docker.build(dockerImage, buildArgs)
        }
    }
}
// runOnNode: a helper that runs the userStages closure on an appropriate node
// i.e., this allows running the same stages on docker and windows
def runOnNode(config, userStages) {
    def buildName = config["Name"]
    def wsDir = "workspace/${env.JOB_NAME}/" \
                 + buildName.replaceAll(" ", "_") + "_${env.BUILD_NUMBER}"
    return {
        node(config["NodeLabel"]) {
            ws(wsDir) {
                try {
                    if(isDockerNode(config["NodeLabel"])) {
                        //the built image should be cached and shared anyway
                        shallowCheckoutGit()
                        print("Calling docker inside in ${pwd()}")
                        buildDocker(config)
                        docker.image(config["DockerImage"]).inside {
                            userStages()
                        }
                    } else {
                        print("Working in ${pwd()}")
                        userStages()
                    }
                } finally {
                    cleanWs(cleanWhenNotBuilt: true, cleanWhenFailure: true,
                            cleanWhenSuccess: true, cleanWhenAborted: true,
                            deleteDirs: true, disableDeferredWipeout: true)
                }
            } //ws
        } //node
    } //return
}

// Canonical way on CMake + Ninja + VS is to source the appropriate vcvarsall script
// before invoking cmake -G Ninja
def getVsBuildEnv(arch, version){
    def localEnv=[]
    def toolDir="${tool 'BuildTools2019'}\\..\\..\\.."
    // get vcvarsall.bat environment
    def envstr = bat returnStdout: true, script: "\"${toolDir}\\VC\\Auxiliary\\Build\\vcvarsall.bat\" ${arch} -vcvars_ver=${version} &set"
    def lines = envstr.split("\r\n")
    for(int i = 0; i < lines.size(); i++) {
        def line = lines[i]
        if(line =~ /^\S+=.*/) {
            localEnv += line
        }
    }
    return localEnv
}

def run(what) {
    if(isUnix()) {
        sh "${what}"
    } else {
        bat "${what}"
    }
}
// quote percent sign for DOS batch, eg. uses in git log --format=%ct
def quoteBat(userStr) {
    def res="@" //disable printing the command itself
    for(int i = 0; i < userStr.size(); i++) {
        def ch = userStr[i]
        if( ch == '%' ) {
            res += "%%"
        } else{
            res += ch
        }
    }
    return res
}
def runWithOutput(what) {
    if(isUnix()) {
        return sh(script: "${what}", returnStdout: true).trim()
    } else {
        return bat(script: "${quoteBat(what)}", returnStdout: true).trim()
    }
}

//##########################################
//the actual build process
//##########################################

// instantiate a build on an appropriate node
def doBuild(Map config) {
    return runOnNode(config, {
        def buildName = config["Name"]
        def buildPreset = config["CmakePreset"]
        def debugPreset = buildPreset.replace("-release", "-debug")
        def buildCmakeArgs = config.getOrDefault("CmakeArgs", "")
        def buildDocs = config.getOrDefault("BuildDocs", false)
        def publishArtifacts = config.getOrDefault("PublishArtifacts", false).toBoolean()
        def buildTestDebug = config.getOrDefault("TestDebug", false) 
        def triggerAbiCheck = config.getOrDefault("TriggerAbiCheck", false)
        def checkLicenses = config.getOrDefault("checkLicenses", false)
        def pipenvExtraArgs = ""
        def pythonExe = isUnix() ? "python" : "py -3.9"

        def buildEnv = []
        def scmVars = [:]

        stage("Git checkout and ENV setup (${buildName})") {
            if(config.containsKey("MsvcVersion")) {
                // visual studio toolset selection via vcvarsall env
                buildEnv = buildEnv + getVsBuildEnv(config["Arch"], config["MsvcVersion"])
                buildEnv.add("MSBUILDDISABLENODEREUSE=1") //fixes spurious windows failures
            }

            scmVars = checkoutGit()

            // For reproducible build set SOURCE_DATE_EPOCH to time of last commit
            def commitTime = runWithOutput("git log --max-count=1 --format=%ct -r origin/main-mirror")
            buildEnv.add("SOURCE_DATE_EPOCH=${commitTime}")
            buildEnv.add("TZ=UTC")
            buildEnv.add("LC_ALL=C.UTF-8")
            buildEnv.add("LANG=C.UTF-8")

            print("DEBUG scmVars=${scmVars}, commitTime=${commitTime}, TZ=${env.TZ}, LC_ALL=${env.LC_ALL} buildEnv=${buildEnv}")

            // save branch name for publishing stage
            gitBranch = scmVars.GIT_BRANCH
            buildEnv.add("GIT_BRANCH=${scmVars.GIT_BRANCH}")
            buildEnv.add("GIT_COMMIT=${scmVars.GIT_COMMIT}")
            buildEnv.add("GIT_URL=${scmVars.GIT_URL}")
        }

        if(checkLicenses) {
            stage("License Check (${buildName})") {
                run "sh ./SilKit/ci/check_licenses.sh"
            }
        }

        def warningsAsError = config.getOrDefault("WarningAsErrors", false).toBoolean()
        if(warningsAsError) {
            print("Enabling Warnings-as-Errors for the current build config")
            buildCmakeArgs +=" -DSILKIT_WARNINGS_AS_ERRORS=ON "
        } else {
            print("Disabling Warnings-as-Errors for the current build config")
        }
        if(buildDocs) {
            buildCmakeArgs +=" -DSILKIT_BUILD_DOCS=ON "
        }
        if(publishArtifacts || buildDocs) {
            buildCmakeArgs +=" -DSILKIT_INSTALL_SOURCE=ON "
        }

        if(config.containsKey("MsvcVersion")) {
            def msvcVersion = config["MsvcVersion"]
            //needed for binary download URL resolution
            buildCmakeArgs += " -D MSVC_TOOLSET_VERSION=${msvcVersion} "
        }

        withEnv(buildEnv) {
            stage("${buildName}: cmake version") {
                run("cmake --version")
            }
            stage("${buildName}: cmake configure for preset ${buildPreset}") {
                    if(buildDocs) {
                        // Install dependencies for documentation
                        configFileProvider([
                            configFile(fileId: 'PYPI_MIRROR', variable: 'PYPI_MIRROR'),
                        ]) {
                            def pypiMirror = readFile(file: PYPI_MIRROR).trim()
                            print("Using pipenv to install docs dependencies")
                            if(!isUnix()) {
                                run("py -3.9 -m pip install pipenv==2022.9.8")
                                pipenvExtraArgs = "--python 3.9"
                            }
                            run("${pythonExe} -m pipenv ${pipenvExtraArgs} install --pypi-mirror  ${pypiMirror} -r SilKit/ci/docker/docs_requirements.txt")
                        }
                    }
                    run("cmake --preset ${buildPreset} ${buildCmakeArgs}")
            }

            stage("${buildName}: cmake build for preset ${buildPreset}") {
                if(buildDocs) {
                    run("${pythonExe} -m pipenv ${pipenvExtraArgs} run cmake --build --preset ${buildPreset}")
                } else {
                    run("cmake --build --preset ${buildPreset}")
                }
            }

            stage("${buildName}: ctest for preset ${buildPreset}") {
                timeout(time: 3, unit: 'MINUTES') {
                    run("ctest --preset ${buildPreset} -R \"^Test\" --output-on-failure")
                    junit("_build/${buildPreset}/**/*gtestresults.xml")
                }
                timeout(time: 10, unit: 'MINUTES') {
                    run("ctest --preset ${buildPreset} -R \"^ITest\" --output-on-failure")
                    junit("_build/${buildPreset}/**/*gtestresults.xml")
                }
            }

            if(globalBuildDebugBin || buildTestDebug) {
                stage("${buildName}: cmake build for preset ${buildPreset} @Debug") {
                    // in Debug builds we only need the library and symbols
                    def debugFlags = ""
                    debugFlags += " -D SILKIT_BUILD_DOCS=OFF "
                    debugFlags += " -D SILKIT_INSTALL_SOURCE=OFF "
                    debugFlags += " -D SILKIT_BUILD_UTILITIES=OFF "
                    debugFlags += " -D SILKIT_BUILD_DEMOS=OFF "

                    run "cmake --preset ${debugPreset} ${debugFlags}"
                    run "cmake --build --preset ${debugPreset}"
                    run "cmake --build --preset ${debugPreset} --target package"
                }
            }
            // run tests for sanitizer builds also in debug mode
            if(buildTestDebug) {
                stage("${buildName}: ctest for preset ${debugPreset}") {
                    timeout(time: 3, unit: 'MINUTES') {
                        run("ctest --preset ${debugPreset} -R \"^Test\" --output-on-failure")
                        junit("_build/${debugPreset}/**/*gtestresults.xml")
                    }
                    timeout(time: 10, unit: 'MINUTES') {
                        run("ctest --preset ${debugPreset} -R \"^ITest\" --output-on-failure")
                        junit("_build/${debugPreset}/**/*gtestresults.xml")
                    }
                }
            }
            stage("${buildName}: packaging artifacts for preset ${buildPreset}") {
                if(publishArtifacts) {
                    run "cmake --build --preset ${buildPreset} --target package"
                    if(globalBuildDebugBin) {
                        run "python ./SilKit/ci/package.py  \"_build/${buildPreset}/${artifactName}-*-Release.zip\" \"_build/${debugPreset}/${artifactName}-*-Debug.zip\""
                        archiveToArtifactory("${artifactName}-.*.zip")
                    } else {
                        archiveToArtifactory("_build/${buildPreset}/${artifactName}-.*.zip")
                    }

                    // safe the debug symbols files on windows/Linux
                    archiveToArtifactory("_build/${debugPreset}/${artifactName}-.*-SYMBOLS.zip")
                    if(!isUnix()) {
                         archiveToArtifactory("_build/${buildPreset}/${artifactName}-.*-SYMBOLS.zip")
                     }
                } else {
                    print("Package publishing disabled: config=${config}")
                }
            }
            if (publishArtifacts && triggerAbiCheck) {
                stage("${buildName}: Triggering ABI Check") {
                    def versionList = []

                    // look for the archive file created in the previous step
                    for (zipFile in findFiles(glob: "**.zip"))
                    {
                        def m = zipFile =~ /^.*SilKit-([0-9]+[.][0-9]+[.][0-9]+)-[^\/]*.zip$/
                        if (!m)
                        {
                            continue
                        }

                        versionList += m[0][1]
                    }

                    def versions = versionList.toSet()

                    if (versions.size() == 0)
                    {
                        echo "No version found for which the ABI check could be triggered!"
                        return
                    }

                    if (versions.size() > 1)
                    {
                        error "Multiple versions found for which the ABI check would be triggered!"
                    }

                    // take the first artifact we found and extract the version from it
                    def silKitVersion = versions.first()
                    echo "Triggering ABI-Check for SIL Kit version ${silKitVersion} (${env.GIT_BRANCH}, ${env.GIT_COMMIT})"

                    build(
                        job: '/SilKit/sil-kit-dev-abi-check/main',
                        wait: false,
                        parameters: [
                            string(name: 'TEST_BRANCH', value: env.GIT_BRANCH),
                            string(name: 'TEST_COMMIT', value: env.GIT_COMMIT),
                            string(name: 'TEST_VERSION', value: silKitVersion)
                        ]
                    )
                }
            }
        }
    })
}

// node main entry. parallel invocation of all builds, packaging
node {
    try {
        properties([
            buildDiscarder(logRotator(numToKeepStr: "${keepNumBuilds}")),
            parameters([
                booleanParam(name: "ForceFullBuild", defaultValue: false,
                    description: "Force a full build with artificat uploads")
                ,booleanParam(name: "ForceArtifactUpload", defaultValue: false,
                    description: "Force uploading artifact uploads")
                ,booleanParam(name: "UseThreadSanitizer", defaultValue: false,
                    description: "Build with thread sanitizer, pelase refer to the  output logs of tests")
                ,booleanParam(name: "UseAddressSanitizer", defaultValue: false,
                    description: "Build with thread sanitizer, pelase refer to the  output logs of tests")
            ])
        ])  

        def doFullBuild = isFullBuildRequired(env.BRANCH_NAME)
        if(params.ForceFullBuild) {
            print("Forcing a full build at user request!")
            doFullBuild = true
        }

        def configNames = []

        if(params.UseAddressSanitizer) {
            print("Building on Ubuntu with -f sanitizer=thread")
            configNames = [
                "Ubuntu-22.04-clang-14-thread-sanitizer"
            ]
        }
        else if (params.UseThreadSanitizer) {
            print("Building on Ubuntu with -f sanitizer=address")
            configNames = [
                "Ubuntu-22.04-clang-14-address-sanitizer"
            ]
        }
        else if(doFullBuild) {
            print("Doing a full build and publishing artifacts on branch ${env.BRANCH_NAME}")
            configNames = [
                "VS2017-Win32",
                "VS2017-Win64",
                "Ubuntu-18.04-gcc",
                "Ubuntu-22.04-clang-14", // most modern compiler, no artifacts
                "Ubuntu-22.04-clang-14-thread-sanitizer", // TSan with most modern compiler, no artifacts
                "Ubuntu-22.04-clang-14-address-sanitizer", // ASan with most modern compiler, no artifacts
                "Ubuntu-22.04-clang-14-undefined-behavior-sanitizer", // UBSan with most modern compiler, no artifacts
            ]
            publishToArtifactory = true
            globalBuildDebugBin = true
        } else {
            print("Doing a minimal build without publishing artifacts on branch ${env.BRANCH_NAME}")
            configNames = [
                "VS2017-Win32", 
		"Ubuntu-22.04-clang-14-thread-sanitizer", // TSan with most modern compiler
                "Ubuntu-22.04-clang-14-address-sanitizer", // ASan with most modern compiler
                "Ubuntu-22.04-clang-14-undefined-behavior-sanitizer", // UBSan with most modern compiler
            ]
        }
        def builds = [:]
        configNames.each {
            def configName = it
            def buildConfig = buildConfigs.find { it.Name == configName}
            if(params.ForceArtifactUpload) {
                print("ForceArtifactUpload: PublishArtifacts is enabled for ${configName}")
                buildConfig["PublishArtifacts"] = true
                globalBuildDebugBin = true
            } else {
                if(!doFullBuild) {
                    print("PublishArtifacts is disabled for ${configName}")
                    buildConfig["PublishArtifacts"] = false
                }
            }
            builds.put(it, doBuild(buildConfig))
        }

        if(params.ForceArtifactUpload) {
            print("Forcing Artifact Upload")
            publishToArtifactory = true
        }

        parallel(builds)

    }
    finally {
        if(publishToArtifactory) {
            stage("Publishing Build Info") {
                print("INFO: publishing artifactory build info for branch ${gitBranch}")
                setBuildRetention(artifactoryBuildInfo)
                artifactoryServer.publishBuildInfo(artifactoryBuildInfo)
            }
        } else {
            stage("Done (No Publishing)") {
                print("INFO: not publishing artifacts")
            }
        }
        cleanWs(cleanWhenNotBuilt: true, cleanWhenFailure: true,
                cleanWhenSuccess: true, cleanWhenAborted: true,
                deleteDirs: true, disableDeferredWipeout: true )
    }
}
