// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post

pipeline {
    agent { label 'rust_nodocker' }

    options {
        disableConcurrentBuilds()
        skipDefaultCheckout(true)
        timeout(time: 45, unit: 'MINUTES')
        timestamps()
    }

    environment {
        CARGO_TERM_COLOR = 'never'
        RUST_BACKTRACE = '1'
        CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"

        BADGE_OWNER = 'MadGobblins'
        BADGE_PROJECT = 'fader_master'
        BADGE_DEFAULT_BRANCH = 'main'
        BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
        COVERAGE_MIN_LINES = '20'
        CARGO_LLVM_COV_VERSION = '0.9.1'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm

                sh '''
                    set -eu

                    git submodule sync --recursive
                    git submodule update --init --recursive

                    rm -rf coverage
                    mkdir -p coverage
                '''
            }
        }

        stage('Setup Rust') {
            steps {
                sh '''
                    set -eu

                    if ! command -v rustup >/dev/null 2>&1; then
                        echo 'ERROR: rustup is required on the Jenkins worker.' >&2
                        exit 1
                    fi

                    rustup toolchain install stable \
                        --profile minimal \
                        --component rustfmt \
                        --component clippy \
                        --component llvm-tools-preview
                    rustup default stable

                    if ! cargo llvm-cov --version 2>/dev/null \
                        | grep -F "cargo-llvm-cov ${CARGO_LLVM_COV_VERSION}" >/dev/null; then
                        cargo install cargo-llvm-cov \
                            --version "${CARGO_LLVM_COV_VERSION}" \
                            --locked
                    fi

                    rustc --version
                    cargo --version
                    rustfmt --version
                    cargo clippy --version
                    cargo llvm-cov --version
                '''
            }
        }

        stage('CI Script Tests') {
            steps {
                sh '''
                    set -eu
                    scripts/test-ci.sh
                '''
            }
        }

        stage('Format') {
            steps {
                sh '''
                    set -eu
                    cargo fmt --all -- --check
                '''
            }
        }

        stage('Check') {
            steps {
                sh '''
                    set -eu
                    cargo check --workspace --all-targets --all-features --locked
                '''
            }
        }

        stage('Tests') {
            steps {
                sh '''
                    set -eu
                    cargo test --workspace --all-targets --all-features --locked
                    : >"coverage/.tests-passed-${BUILD_NUMBER}"
                '''
            }
        }

        stage('Coverage') {
            steps {
                sh '''
                    scripts/ci-run-coverage.sh \
                        "${COVERAGE_MIN_LINES}" \
                        coverage/llvm-cov-summary.json \
                        "coverage/.coverage-ready-${BUILD_NUMBER}" \
                        coverage/coverage-status.txt
                '''
            }
        }

        stage('Documentation') {
            steps {
                sh '''
                    set -eu
                    cargo test --workspace --doc --all-features --locked
                    RUSTDOCFLAGS='-D warnings' \
                        cargo doc --workspace --no-deps --all-features --locked
                '''
            }
        }

        stage('Clippy') {
            steps {
                sh '''
                    set -eu
                    cargo clippy \
                        --workspace \
                        --all-targets \
                        --all-features \
                        --locked \
                        -- \
                        -D warnings
                '''
            }
        }

        stage('Build Release') {
            steps {
                sh '''
                    set -eu
                    cargo build --workspace --release --all-features --locked

                    BINARY="${CARGO_TARGET_DIR}/release/fader_master"
                    if [ ! -x "${BINARY}" ]; then
                        echo "ERROR: expected release binary is missing or not executable: ${BINARY}" >&2
                        exit 1
                    fi

                    ls -lh "${BINARY}"
                    file "${BINARY}" || true
                    ldd "${BINARY}" || true
                '''
            }
        }
    }

    post {
        cleanup {
            script {
                sh '''
                    set -eu
                    scripts/ci-finalize-badges.sh "${BUILD_NUMBER}"
                '''

                archiveArtifacts(
                    allowEmptyArchive: false,
                    artifacts: 'coverage/coverage.svg,coverage/test.svg,coverage/version.svg',
                    fingerprint: true
                )

                def ciBranch = env.BRANCH_NAME
                if (!ciBranch && env.GIT_BRANCH) {
                    ciBranch = env.GIT_BRANCH
                        .replaceFirst(/^refs\/remotes\/origin\//, '')
                        .replaceFirst(/^origin\//, '')
                }
                if (ciBranch == env.BADGE_DEFAULT_BRANCH) {
                    sh '''
                        set -eu
                        scripts/ci-publish-badges.sh \
                            "${BADGE_PUBLICATION_ROOT}" \
                            "${BADGE_OWNER}" \
                            "${BADGE_PROJECT}" \
                            "${BADGE_DEFAULT_BRANCH}" \
                            coverage test version
                    '''
                } else if (ciBranch) {
                    echo "Not publishing mutable badges from non-default branch ${ciBranch}."
                } else {
                    echo 'Not publishing mutable badges: BRANCH_NAME and GIT_BRANCH are unavailable.'
                }

                def coverageStatus = fileExists('coverage/coverage-status.txt')
                    ? readFile('coverage/coverage-status.txt').trim()
                    : "Line coverage: unavailable; required minimum: ${env.COVERAGE_MIN_LINES}%; reason: the coverage stage did not produce a status"
                def passed = currentBuild.currentResult == 'SUCCESS'
                publishChecks(
                    conclusion: passed ? 'SUCCESS' : 'FAILURE',
                    name: 'Rust CI',
                    summary: passed ? 'fader_master passed CI.' : 'fader_master failed CI.',
                    text: "Formatting, checks, tests, coverage, documentation, warning-strict Clippy, release build, and badge generation were evaluated. ${coverageStatus}",
                    title: passed ? 'Build Successful' : 'Build Failed'
                )
                echo "${passed ? 'fader_master passed CI.' : 'fader_master CI failed.'} ${coverageStatus}"

                sh 'rm -f coverage/coverage-status.txt'
            }

            deleteDir()
        }
    }
}
