// Jenkins CI for Archive/rping
//
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
//
// rping is a Rust ICMP ping CLI. CI deliberately does not execute a live ping
// because raw ICMP sockets may require elevated privileges/capabilities.

pipeline {
    agent { label 'rust_nodocker' }

    options {
        skipDefaultCheckout(true)
        timestamps()
        disableConcurrentBuilds()
    }

    environment {
        CARGO_TERM_COLOR = 'never'
        RUST_BACKTRACE = '1'
        RUST_MSRV = '1.70.0'
        CARGO_LLVM_COV_VERSION = '0.9.0'
        BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
        BADGE_OWNER = 'Archive'
        BADGE_PROJECT = 'rping'
        DEFAULT_BRANCH = 'main'
    }

    stages {
        stage('Checkout') {
            steps {
                sh '''
                    set -eu
                    rm -rf coverage
                    mkdir -p coverage
                '''

                checkout scm

                sh '''
                    set -eu

                    git submodule sync --recursive
                    git submodule update --init --recursive
                '''
            }
        }

        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 installs the version and components from rust-toolchain.toml.
                    # Do not change the shared worker's default toolchain.
                    rustup show active-toolchain

                    rustup toolchain install "$RUST_MSRV" --profile minimal

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

        stage('Setup Coverage Tool') {
            steps {
                sh '''
                    set -eu

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

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

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

        stage('Minimum Supported Rust') {
            steps {
                sh '''
                    set -eu
                    cargo "+$RUST_MSRV" check --locked --all-targets --all-features
                '''
            }
        }

        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 -- -D warnings
                '''
            }
        }

        stage('Build Release') {
            steps {
                sh '''
                    set -eu
                    cargo build --locked --release --all-features
                    test -x target/release/rping
                '''
            }
        }

        stage('Coverage') {
            steps {
                sh '''
                    set -eu

                    summary=coverage/coverage-summary.json
                    cargo llvm-cov \
                        --locked \
                        --all-features \
                        --all-targets \
                        --json \
                        --summary-only \
                        --output-path "$summary" \
                        --fail-under-lines 40
                    test -s "$summary"

                    coverage_value="$(python3 - "$summary" <<'PY'
import json
import math
import sys

with open(sys.argv[1], encoding="utf-8") as report:
    value = json.load(report)["data"][0]["totals"]["lines"]["percent"]
if isinstance(value, bool) or not isinstance(value, (int, float)):
    raise SystemExit("overall line coverage is not numeric")
if not math.isfinite(value) or not 0 <= value <= 100:
    raise SystemExit("overall line coverage is outside 0 through 100")
print(value)
PY
                    )"
                    scripts/ci-coverage-badges.sh coverage --value "$coverage_value"
                    rm -f "$summary"
                    : > "coverage/.coverage-ready-$BUILD_NUMBER"
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'rping CI',
                summary: 'rping passed CI.',
                text: 'Formatting, MSRV and current-toolchain checks, tests, Clippy, the release build, coverage floor, and badge generation completed successfully.',
                title: 'Build Successful'
            )
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'rping CI',
                summary: 'rping failed CI.',
                text: 'A Rust check, test, coverage floor, or badge step failed. Cleanup publishes badges that reflect this build.',
                title: 'Build Failed'
            )
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'rping CI',
                summary: 'rping CI is unstable.',
                text: 'The Jenkins build is unstable. Cleanup publishes badges that reflect this build.',
                title: 'Build Unstable'
            )
        }

        cleanup {
            sh '''
                set -eu

                if [ -f "coverage/.tests-passed-$BUILD_NUMBER" ]; then
                    scripts/ci-coverage-badges.sh test --value passing
                else
                    scripts/ci-coverage-badges.sh test --value failing
                fi

                if [ ! -f "coverage/.coverage-ready-$BUILD_NUMBER" ]; then
                    scripts/ci-coverage-badges.sh coverage --value -
                fi

                version="$(cargo metadata --locked --no-deps --format-version 1 | python3 -c '
import json
import sys

metadata = json.load(sys.stdin)
resolve = metadata.get("resolve")
root = resolve.get("root") if isinstance(resolve, dict) else None
packages = metadata["packages"]
if root is not None:
    packages = [package for package in packages if package["id"] == root]
if len(packages) != 1:
    raise SystemExit("could not resolve one authoritative package version")
print(packages[0]["version"])
')"
                scripts/ci-coverage-badges.sh version --value "$version"

                rm -f coverage/coverage-summary.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
                    '''
                }
            }
        }
    }
}
