/* 
CAUTION: THIS IS A SAMPLE JENKINS SCRIPT FOR REFERENCE PURPOSE ONLY AND NOT AN IDMC PRODUCT OFFERING. 
THIS SHOULD BE USED ONLY FOR INFORMATION PURPOSES AND INFORMATICA WILL NOT PROVIDE SUPPORT OR ENHANCEMENTS ON THIS SCRIPT. 
*/

node {
    stage('IDMC Code Deployment - Checkout') {
        sh 'echo "Building Dev Branch"'
        checkout([
            $class: 'GitSCM',
            branches: [[name: 'dev']],
            doGenerateSubmoduleConfigurations: false,
            extensions: [],
            submoduleCfg: [],
            userRemoteConfigs: [[credentialsId: 'Github_Key', url: 'https://token@REPOURL']]
        ])
    }

    stage("Get changes and Cherrypick to QA branch") {
        // This script uses the Jenkins plugin LastChanges
        def publisher = LastChanges.getLastChangesPublisher(
            "LAST_SUCCESSFUL_BUILD",
            "SIDE",
            "LINE",
            true,
            true,
            "",
            "",
            "",
            "",
            ""
        )
        publisher.publishLastChanges()
        listOfCommits = []
        def changes = publisher.getLastChanges()
        def currentCommit
        println("Entering Commit loop")
        for (commit in changes.getCommits()) {
            println("Commit Hash:")
            currentCommit = commit.commitInfo.commitId
            listOfCommits.add(currentCommit)
            println(currentCommit)
        }
        checkout([
            $class: 'GitSCM',
            branches: [[name: 'QA']],
            doGenerateSubmoduleConfigurations: false,
            extensions: [],
            submoduleCfg: [],
            userRemoteConfigs: [[credentialsId: 'Github_Key', url: 'https://token@REPOURL']]
        ])
        for (commitToCherryPick in listOfCommits) {
            println("Commit Hash to cherry pick for QA:")
            println(commitToCherryPick)
            sh "git cherry-pick ${commitToCherryPick}"
            sh 'git push origin HEAD:QA'
            /* This is an API call to a published Cloud Application Process which is a wrapper to the Login API call and the pull by commit hash API call. 
            This can be replaced with 2 separate API calls if needed */
            sh """
                curl --location --request POST 'https://na1.ai.dm-us.informaticacloud.com/active-bpel/public/rt/8jE1pxcZr0Mj2MiIEjrDi6/Process_PullByCommit' \
                --header 'Content-Type: application/json' \
                --data '{"commitHash":"${commitToCherryPick}"}'
            """
        }
    }
}