pipeline {
    agent any

    environment {
        COVERITY_URL = 'https://coverity.etechtips.com'
        COVERITY_STREAM = 'agone-full'
        COVERITY_PR_STREAM = 'agone-pr'
        // Add Coverity binaries to PATH if not globally set on the Jenkins agent
        PATH = "/opt/coverity/analysis/bin:${env.PATH}"

        // Full-build baseline artifact
        COVERITY_BASELINE_ARCHIVE = 'agone-full-cov-int.tar.gz'
   
        //For a Multibranch Pipeline 
        AGONE_FULL_JOB = 'agone/main'
    }

    options {
        timestamps()
        timeout(time: 2, unit: 'HOURS')
    }

    stages {
        // =================================================================
        // STAGE 1: AGONE-FULL (Triggers on main/master branch commits or nightlies)
        // =================================================================
        stage('Agone Full Build & Analysis') {
            when {
                // Adjust this condition based on your default branch name
                branch 'main' 
            }
            steps {
                script {
                    echo "Starting agone-full build..."
                    echo "The current branch is: ${env.BRANCH_NAME}"                 
                    
                    // 1. Clean previous Coverity intermediate directory
                    sh 'rm -rf cov-int'

		    // Clean Bazel outputs
                    sh 'bazel clean'

                    // 2. Run full Bazel build wrapped in cov-build
                    // --spawn_strategy=standalone ensures Coverity intercepts compiler processes
                    sh '''
                        cov-build --dir cov-int --bazel \
bazel build --spawn_strategy=standalone //:run
                    '''

                    // 3. Analyze captured code
                    sh 'cov-analyze --dir cov-int'

                    // 4. Commit results to Coverity Connect
                    withCredentials([usernamePassword(
                        credentialsId: 'coverity-credentials', 
                        passwordVariable: 'COV_PASSWORD', 
                        usernameVariable: 'COV_USER'
                    )]) {
                        sh '''
                            cov-commit-defects --dir cov-int \
                                --url "${COVERITY_URL}" \
                                --stream "${COVERITY_STREAM}" \
                                --user "${COV_USER}" \
                                --password "${COV_PASSWORD}"
                        '''
                    }
                    // 5. Package the completed  full-build intermediate directory
                    sh '''
                            rm -f "${COVERITY_BASELINE_ARCHIVE}"
                            tar -czf "${COVERITY_BASELINE_ARCHIVE}" cov-int
                            test -s "${COVERITY_BASELINE_ARCHIVE}"

                    '''

                    // 6. Store Baseline as a jenkins artifact
                    archiveArtifacts (
                         artifacts: "${COVERITY_BASELINE_ARCHIVE}",
                         fingerprint: true,
                         onlyIfSuccessful: true
                    )

                }
            }
        }

        // =================================================================
        // STAGE 2: AGONE-PR (Triggers on Pull Request branches)
        // =================================================================
        stage('Agone PR Build & Analysis') {
            when {
                // Matches Multibranch Pipeline PR branch patterns (e.g., PR-123)
                changeRequest() 
                // Triggers if running on any branch that is not 'main'
                //not { branch 'main' }
            }
            steps {
                script {
                    echo "Starting agone-pr build..."
                    echo "The current branch is: ${env.BRANCH_NAME}"                 
                   
                    // 1. Determine target branch and fetch changes
                    def targetBranch = env.CHANGE_TARGET ?: 'main'

                    sh """
                        git fetch origin \
                            +refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}
                    """
                    def mergeBase = sh(
                        script: "git merge-base HEAD origin/${targetBranch}",
                        returnStdout: true
                    ).trim()

                    echo "Merge base: ${mergeBase}"

                    def changedFiles = sh(
                        script: "git diff --name-only ${mergeBase} HEAD",
                        returnStdout: true
                    ).trim()

                    if (!changedFiles) {
                        echo "No files modified in this PR. Skipping build."
                        return
                    }

                    // Write changed files to a temporary file for Coverity / Bazel querying
                    writeFile file: 'changed_files.txt', text: changedFiles

                    // 3. Query Bazel reverse dependencies to find affected targets
                    // Formats file paths into a space-separated list for set() query
                    def bazelQueryTargetSet = changedFiles.split('\n').join(' ')
                    def affectedTargets = sh(
                        script: "bazel query --keep_going \"rdeps(//..., set(${bazelQueryTargetSet}))\" 2>/dev/null || true",
                        returnStdout: true
                    ).trim()

                    if (!affectedTargets) {
                        echo "No Bazel targets affected by modified files. Skipping build."
                        return
                    }

                    echo "Affected Bazel targets:\n${affectedTargets}"

                    copyArtifacts (
                         projectName: "${AGONE_FULL_JOB}",
                         selector: last_successful(), 
                         filter: "${COVERITY_BASELINE_ARCHIVE}",
                         fingerprintArtifacts: true
                    )

                    // 4a. recover nightly pr
                    sh '''
                       rm -rf cov-int-pr baseline-cov-int 
                       mkdir baseline-cov-int 
                       tar -xzf "${COVERITY_BASELINE_ARCHIVE}" \
                           -C  baseline-cov-int 
                       test -d baseline-cov-int/cov-int

                       mv baseline-cov-int/cov-int cov-int-pr 
                       rmdir baseline-cov-int 
                    '''

                    // 5. Build only the affected targets wrapped in cov-build
                    sh """
                        cov-build --dir cov-int-pr --bazel \
                            bazel build --spawn_strategy=standalone ${affectedTargets.replaceAll('\n', ' ')}
                    """

                    // 6. Run fast desktop analysis on only changed files
                    sh '''
                        cov-run-desktop --dir cov-int-pr \
                            --target-url "${COVERITY_URL}" \
                            --stream "${COVERITY_PR_STREAM}" \
                            ${changedFiles.replaceAll('\n', ' ')}
                    '''
                }
            }
        }
    }

    post {
        always {
            // Clean up workspace or temporary Bazel artifacts if required
            echo "Pipeline complete."
        }
        failure {
            echo "Pipeline failed. Check build logs for Bazel or Coverity errors."
        }
    }
}
