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

pipeline {
    agent { label 'rust_nodocker' }

    environment {
        CARGO_TERM_COLOR = 'never'
        RUST_BACKTRACE = '1'
        CARGO_AUDIT_VERSION = '0.22.2'
        CARGO_DENY_VERSION = '0.20.2'
        CARGO_TARPAULIN_VERSION = '0.37.5'
        BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
        BADGE_OWNER = 'Dandaedre'
        BADGE_PROJECT = 'rust_autobadges'
        DEFAULT_BRANCH = 'main'
    }

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

                sh '''
                    set -eu

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

                    rm -rf coverage
                    mkdir -p coverage
                    rm -f target/release/rust_autobadges
                '''
            }
        }

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

                    if ! command -v rustup >/dev/null 2>&1; then
                        echo "ERROR: rustup is not installed on this worker." >&2
                        exit 1
                    fi

                    rustup toolchain install stable \
                        --profile minimal \
                        --component rustfmt \
                        --component clippy

                    rustup default stable

                    rustc --version
                    cargo --version
                '''
            }
        }

        stage('Setup Supply-Chain Tools') {
            steps {
                sh '''
                    set -eu

                    audit_version="$(cargo audit --version 2>/dev/null | awk '{print $2}' || true)"
                    if [ "$audit_version" != "$CARGO_AUDIT_VERSION" ]; then
                        cargo install --locked --version "$CARGO_AUDIT_VERSION" cargo-audit
                    fi

                    deny_version="$(cargo deny --version 2>/dev/null | awk '{print $2}' || true)"
                    if [ "$deny_version" != "$CARGO_DENY_VERSION" ]; then
                        cargo install --locked --version "$CARGO_DENY_VERSION" cargo-deny
                    fi

                    cargo audit --version
                    cargo deny --version

                    tarpaulin_version="$(cargo tarpaulin --version 2>/dev/null | awk '{print $2}' || true)"
                    if [ "$tarpaulin_version" != "$CARGO_TARPAULIN_VERSION" ]; then
                        cargo install --locked --version "$CARGO_TARPAULIN_VERSION" cargo-tarpaulin
                    fi
                    cargo tarpaulin --version
                '''
            }
        }

        stage('Cargo Audit') {
            steps {
                sh '''
                    set -eu
                    cargo audit --deny warnings
                '''
            }
        }

        stage('Dependency Policy') {
            steps {
                sh '''
                    set -eu
                    cargo deny check
                '''
            }
        }

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

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

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

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

        stage('Coverage') {
            steps {
                sh '''
                    set -eu
                    cargo tarpaulin
                    test -s coverage/tarpaulin-report.json
                    target/release/rust_autobadges badge coverage \
                        --summary coverage/tarpaulin-report.json
                    rm -f coverage/tarpaulin-report.json
                    : > "coverage/.coverage-ready-$BUILD_NUMBER"
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Rust CI',
                summary: 'rust_autobadges passed CI.',
                text: 'Security policy, formatting, tests, Clippy, coverage and badge generation completed successfully.',
                title: 'Build Successful'
            )
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Rust CI',
                summary: 'rust_autobadges failed CI.',
                text: 'A Rust check, test, coverage floor, or badge step failed. Cleanup publishes failing and neutral status badges.',
                title: 'Build Failed'
            )
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Rust CI',
                summary: 'rust_autobadges CI is unstable.',
                text: 'The build is unstable; cleanup publishes badges that reflect this build.',
                title: 'Build Unstable'
            )
        }

        cleanup {
            sh '''
                set -eu

                badge_bin=target/release/rust_autobadges
                if [ ! -x "$badge_bin" ]; then
                    cargo build --locked --release --all-features
                fi

                if [ -f "coverage/.tests-passed-$BUILD_NUMBER" ]; then
                    "$badge_bin" badge test --value passing
                else
                    "$badge_bin" badge test --value failing
                fi

                if [ ! -f "coverage/.coverage-ready-$BUILD_NUMBER" ]; then
                    "$badge_bin" badge coverage --value -
                fi
                "$badge_bin" badge version

                rm -f coverage/tarpaulin-report.json \
                    "coverage/.tests-passed-$BUILD_NUMBER" \
                    "coverage/.coverage-ready-$BUILD_NUMBER"

                for badge in version test coverage; do
                    file="coverage/$badge.svg"
                    test -f "$file"
                    test ! -L "$file"
                    test -s "$file"
                done
                count="$(find coverage -maxdepth 1 -type f -name '*.svg' | wc -l | tr -d ' ')"
                test "$count" = 3
            '''

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

            script {
                if (!env.BRANCH_NAME) {
                    error('BRANCH_NAME is required; badge publication expects a Jenkins multibranch job.')
                }
                if (env.BRANCH_NAME == env.DEFAULT_BRANCH) {
                    sh '''
                        scripts/publish-coverage-badges.sh \
                            "$BADGE_PUBLICATION_ROOT" \
                            "$BADGE_OWNER" \
                            "$BADGE_PROJECT" \
                            "$DEFAULT_BRANCH" \
                            version test coverage
                    '''
                }
            }
        }
    }
}
