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

pipeline {
    agent { label 'rust_no_docker' }

    options {
        // We handle checkout explicitly below.
        skipDefaultCheckout(true)
    }

    environment {
        PYTHONUNBUFFERED = '1'
    }

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

                sh '''
                    set -eu

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

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

                    echo "System:"
                    uname -a

                    echo
                    echo "Architecture:"
                    uname -m

                    echo
                    echo "Git:"
                    git --version

                    echo
                    echo "Python:"
                    python3 --version

                    echo
                    echo "Repository:"
                    git status --short
                '''
            }
        }

        stage('Validate CI Tools') {
            steps {
                sh '''
                    set -eu

                    if ! command -v python3 >/dev/null 2>&1; then
                        echo "ERROR: python3 is required for Config Central CI." >&2
                        exit 1
                    fi

                    if [ ! -f tools/check_powershell.py ]; then
                        echo "ERROR: tools/check_powershell.py is missing." >&2
                        exit 1
                    fi

                    echo "Python validator found."
                '''
            }
        }

        stage('Validate PowerShell Sources') {
            steps {
                sh '''
                    set -eu

                    echo "Running lightweight PowerShell integrity checks..."
                    echo

                    python3 tools/check_powershell.py
                '''
            }
        }

        stage('Validate JSON') {
            steps {
                sh '''
                    set -eu

                    echo "Validating JSON files..."
                    echo

                    python3 - <<'PY'
import json
import pathlib

paths = sorted(pathlib.Path('.').glob('schemas/*.json'))
paths += sorted(pathlib.Path('.').glob('profiles/*.json'))
paths += sorted(pathlib.Path('.').glob('machines/*.json'))
if not paths:
    raise SystemExit('ERROR: no JSON contracts or manifests found.')
for path in paths:
    with path.open(encoding='utf-8') as stream:
        json.load(stream)
    print(f'OK: {path}')
PY
                '''
            }
        }

        stage('Repository Sanity') {
            steps {
                sh '''
                    set -eu

                    echo "Tracked PowerShell files:"
                    echo

                    ps_files="$(git ls-files -- '*.ps1' '*.psm1' '*.psd1')"
                    if [ -z "${ps_files}" ]; then
                        echo "ERROR: no tracked PowerShell files found." >&2
                        exit 1
                    fi
                    echo "${ps_files}"

                    for required in install.ps1 bootstrap.ps1 cc.ps1 schemas/profile.schema.json schemas/machine.schema.json; do
                        if [ ! -s "${required}" ]; then
                            echo "ERROR: required file is missing or empty: ${required}" >&2
                            exit 1
                        fi
                    done

                    echo
                    echo "Repository sanity checks passed."
                '''
            }
        }

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

                    echo "Checking repository hygiene..."
                    echo

                    failed=0
                    if git grep -n -e '^<<<<<<< ' -e '^=======$' -e '^>>>>>>> ' -- '*.ps1' '*.psm1' '*.md' '*.json'; then
                        echo >&2
                        echo "ERROR: unresolved merge conflict marker found." >&2
                        failed=1
                    else
                        echo "No merge conflict markers found."
                    fi

                    suspicious="$(git ls-files | grep -E '[.](tmp|bak|old|orig|rej)$' || true)"
                    if [ -n "${suspicious}" ]; then
                        echo >&2
                        echo "WARNING: suspicious tracked backup/temp files:"
                        echo "${suspicious}"
                    else
                        echo "No obvious backup/temp files tracked."
                    fi

                    if [ "${failed}" -ne 0 ]; then
                        exit 1
                    fi

                    echo
                    echo "Repository hygiene checks passed."
                '''
            }
        }

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

                    echo
                    echo "========================================"
                    echo " Config Central CI validation complete"
                    echo "========================================"
                    echo
                    echo "Checks performed:"
                    echo "  - Git checkout"
                    echo "  - Python availability"
                    echo "  - PowerShell structural integrity"
                    echo "  - JSON schemas and manifests"
                    echo "  - Required project files"
                    echo "  - Merge conflict detection"
                    echo "  - Repository hygiene"
                    echo
                    echo "NOTE:"
                    echo "  PowerShell/CoreCLR cannot currently run"
                    echo "  on this Jenkins FreeBSD worker."
                    echo
                    echo "  CI therefore performs static checks here."
                    echo "  Pester and real WinGet/elevation tests must"
                    echo "  run on a disposable Windows worker."
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Config Central CI',
                summary: 'Config Central passed all CI integrity checks.',
                text: 'Static PowerShell validation, JSON contract checks, and repository hygiene checks completed successfully. Windows runtime tests are intentionally separate.',
                title: 'Config Central validation successful'
            )
            echo '✅ Config Central integrity checks passed.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Config Central CI',
                summary: 'Config Central failed CI.',
                text: 'A checkout, PowerShell structural, JSON contract, or repository hygiene check failed. Check the Jenkins log.',
                title: 'Config Central CI failed'
            )
            echo '❌ Config Central integrity checks failed.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Config Central CI',
                summary: 'Config Central CI is unstable.',
                text: 'The Jenkins build completed with an unstable status.',
                title: 'Config Central CI unstable'
            )
            echo '⚠️ Config Central CI is unstable.'
        }

        always {
            echo 'CI finished.'
        }
    }
}
