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

pipeline {
    agent { label 'rust_no_docker' }

    environment {
        CARGO_TERM_COLOR = 'always'
        RUST_BACKTRACE = '1'

        // CI gets its own Cargo home. This prevents ~/.cargo/config*
        // from injecting host-specific linker options.
        CARGO_HOME = "${WORKSPACE}/.ci-cargo-home"

        // Keep CI artifacts separate from local/project builds.
        CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"

        // Explicitly use the native FreeBSD compiler/linker.
        CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER = 'cc'

        // Explicitly neutralize environment-provided Rust flags.
        RUSTFLAGS = ''
        CARGO_ENCODED_RUSTFLAGS = ''
    }

    stages {
        stage('Checkout') {
            steps {
                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

                    echo "Ensuring stable Rust is available..."

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

                    rustup default stable

                    # ---------------------------------------------------------
                    # Prepare isolated Cargo environment
                    # ---------------------------------------------------------

                    rm -rf "${CARGO_HOME}"
                    mkdir -p "${CARGO_HOME}"

                    rm -rf "${CARGO_TARGET_DIR}"
                    mkdir -p "${CARGO_TARGET_DIR}"

                    # Cargo discovers .cargo/config* by walking upward from the
                    # current working directory. We therefore invoke Cargo from
                    # a neutral directory outside the repository.
                    CI_RUN_DIR="/tmp/idlefox-ci-${BUILD_NUMBER}"

                    rm -rf "${CI_RUN_DIR}"
                    mkdir -p "${CI_RUN_DIR}"

                    echo "${CI_RUN_DIR}" > .ci-run-dir

                    # ---------------------------------------------------------
                    # Information
                    # ---------------------------------------------------------

                    echo
                    echo "Rust:"
                    rustc --version

                    echo
                    echo "Cargo:"
                    cargo --version

                    echo
                    echo "rustfmt:"
                    rustfmt --version

                    echo
                    echo "Clippy:"
                    cargo clippy --version

                    echo
                    echo "Compiler:"
                    cc --version

                    echo
                    echo "Rust target:"
                    rustc -vV

                    echo
                    echo "Cargo home:"
                    echo "${CARGO_HOME}"

                    echo
                    echo "Cargo target directory:"
                    echo "${CARGO_TARGET_DIR}"

                    echo
                    echo "Neutral Cargo working directory:"
                    cat .ci-run-dir

                    echo
                    echo "Repository Cargo configuration files:"
                    find "${WORKSPACE}" \
                        -path '*/.cargo/config' \
                        -o \
                        -path '*/.cargo/config.toml' \
                        2>/dev/null || true

                    echo
                    echo "Any mold references in repository Cargo configuration:"
                    if [ -d "${WORKSPACE}/.cargo" ]; then
                        grep -Rni 'mold' "${WORKSPACE}/.cargo" || true
                    fi

                    echo
                    echo "CI linker:"
                    echo "${CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER}"
                '''
            }
        }

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

                    CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
                    cd "${CI_RUN_DIR}"

                    echo "Checking Rust formatting..."

                    cargo fmt \
                        --manifest-path "${WORKSPACE}/Cargo.toml" \
                        --all \
                        -- \
                        --check
                '''
            }
        }

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

                    CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
                    cd "${CI_RUN_DIR}"

                    echo "Checking all IdleFox targets..."

                    cargo check \
                        --manifest-path "${WORKSPACE}/Cargo.toml" \
                        --all-targets \
                        --all-features
                '''
            }
        }

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

                    CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
                    cd "${CI_RUN_DIR}"

                    echo "Running IdleFox tests..."

                    cargo test \
                        --manifest-path "${WORKSPACE}/Cargo.toml" \
                        --all-targets \
                        --all-features
                '''
            }
        }

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

                    CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
                    cd "${CI_RUN_DIR}"

                    echo "Running Clippy..."

                    cargo clippy \
                        --manifest-path "${WORKSPACE}/Cargo.toml" \
                        --all-targets \
                        --all-features
                '''
            }
        }

        stage('Check Benchmarks') {
            steps {
                sh '''
                    set -eu

                    CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
                    cd "${CI_RUN_DIR}"

                    echo "Checking benchmark compilation..."

                    cargo check \
                        --manifest-path "${WORKSPACE}/Cargo.toml" \
                        --benches \
                        --all-features
                '''
            }
        }

        stage('Build Release') {
            steps {
                sh '''
                    set -eu

                    CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
                    cd "${CI_RUN_DIR}"

                    echo "Building IdleFox release..."

                    cargo build \
                        --manifest-path "${WORKSPACE}/Cargo.toml" \
                        --release \
                        --all-features

                    echo
                    echo "Release build completed."

                    BINARY="${CARGO_TARGET_DIR}/release/idlefox"

                    if [ ! -f "${BINARY}" ]; then
                        echo "ERROR: expected release binary was not produced:"
                        echo "${BINARY}"
                        exit 1
                    fi

                    echo
                    echo "Release binary:"
                    ls -lh "${BINARY}"

                    echo
                    echo "Binary type:"
                    file "${BINARY}" || true
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Rust CI',
                summary: 'IdleFox passed all CI checks.',
                text: 'Formatting, compilation checks, tests, Clippy, benchmark compilation, and release build completed successfully using the native FreeBSD linker.',
                title: 'Build Successful'
            )

            echo '✅ IdleFox passed all CI checks.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Rust CI',
                summary: 'IdleFox failed CI.',
                text: 'Formatting, compilation, tests, Clippy, benchmarks, or the release build failed. Check the Jenkins log.',
                title: 'Build Failed'
            )

            echo '❌ IdleFox CI failed.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Rust CI',
                summary: 'IdleFox CI is unstable.',
                text: 'The Jenkins build completed with an unstable status.',
                title: 'Build Unstable'
            )

            echo '⚠️ IdleFox CI is unstable.'
        }

        always {
            sh '''
                echo "Cleaning IdleFox CI environment..."

                if [ -f .ci-run-dir ]; then
                    CI_RUN_DIR="$(cat .ci-run-dir)"
                    rm -rf "${CI_RUN_DIR}"
                fi

                rm -f .ci-run-dir
                rm -rf .ci-cargo-home

                # Keep target-ci for now so Jenkins retains incremental
                # compilation between builds. Uncomment to make every build
                # completely clean:
                #
                # rm -rf target-ci
            '''
        }
    }
}