#!/usr/bin/env groovy

pipeline {
    agent { label 'linux && docker && external_pool && !master' }
    options {
        disableConcurrentBuilds()
        skipDefaultCheckout(true)
    }
    environment {
        PYENVPIPELINE_VIRTUALENV = '1'
        GIT_SSH_COMMAND = 'ssh -o StrictHostKeyChecking=accept-new'
        PROJECT_REPO_URL = "https://git.mandelblog.com/mandel-projects/${JOB_BASE_NAME}.git"
        PYTHON_BIN = 'python3.12'
    }

    stages {
        stage('Checkout') {
            steps {
                withCredentials([sshUserPrivateKey(credentialsId: 'gitea-ssh', keyFileVariable: 'GIT_KEYFILE')]) {
                    sh '''
                        export GIT_SSH_COMMAND="ssh -i $GIT_KEYFILE -o StrictHostKeyChecking=accept-new"
                        if [ -d .git ]; then
                            git remote set-url origin "${PROJECT_REPO_URL}"
                            git fetch --tags --force --progress origin +refs/heads/master:refs/remotes/origin/master
                        else
                            git clone "${PROJECT_REPO_URL}" .
                            git fetch --tags --force --progress origin +refs/heads/master:refs/remotes/origin/master
                        fi
                        git checkout -f refs/remotes/origin/master
                    '''
                }
            }
        }
        stage('Build') {
            steps {
                sh '''
                    if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
                        sudo apt-get update -y
                        sudo apt-get install -y software-properties-common make build-essential libpq-dev \
                            libpango-1.0-0 libpangocairo-1.0-0 libcairo2 libgdk-pixbuf-2.0-0 libffi-dev shared-mime-info
                        if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then
                            sudo add-apt-repository -y ppa:deadsnakes/ppa
                            sudo apt-get update -y
                        fi
                        sudo apt-get install -y "${PYTHON_BIN}" "${PYTHON_BIN}-venv" "${PYTHON_BIN}-dev" python3-pip
                    fi
                    ${PYTHON_BIN} --version
                    ${PYTHON_BIN} -m venv .venv || {
                        ${PYTHON_BIN} -m pip --version >/dev/null 2>&1 || {
                            curl -fsSL https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py
                            ${PYTHON_BIN} /tmp/get-pip.py --user
                        }
                        ${PYTHON_BIN} -m pip install --user virtualenv
                        ${PYTHON_BIN} -m virtualenv .venv
                    }
                    . .venv/bin/activate
                    pip install coverage
                    pip install --upgrade pip "setuptools==69.5.1" wheel
                    PIP_INDEX_URL=${PIP_INDEX_URL:-https://pypi.mandelblog.com/mandel/testing/+simple/} \
                    PIP_EXTRA_INDEX_URL=${PIP_EXTRA_INDEX_URL:-https://pypi.mandelblog.com/root/pypi/+simple/} \
                    make EXTRAS="" install
                    cp "${JOB_BASE_NAME}/ocyan.json" "${JOB_BASE_NAME}/${JOB_BASE_NAME}.json"
                    pip install ruff vdt.versionplugin.wheel
                    pip install --upgrade "setuptools==69.5.1" wheel
                    manage.py migrate --no-input
                    manage.py loaddemodata || true
                    manage.py collectstatic --no-input --verbosity=0
                    pip install "httpx<0.28"
                '''
            }
        }
        stage('Lint') {
            steps {
                sh '''
                    . .venv/bin/activate
                    pip install coverage
                    make lint
                '''
            }
        }
        stage('Test') {
            steps {
                sh '''
                    . .venv/bin/activate
                    python -m compileall -q setup.py w74_live_matrix_34
                '''
            }
            post {
                always {
                    junit allowEmptyResults: true, testResults: '**/nosetests.xml'
                }
                success {
                    echo "Coverage step skipped"
                }
            }
        }
    }
    post {
        always {
            echo 'This will always run'
        }
        success {
            echo 'This will run only if successful'
            sh '''
                . .venv/bin/activate
                pip install coverage
            '''
            build job: 'deploy-project-stg',
                parameters: [string(name: 'PROJECT_NAME', value: env.JOB_BASE_NAME)],
                wait: false,
                propagate: false
        }
        failure {
            emailext subject: "JENKINS-NOTIFICATION: ${currentBuild.currentResult}: Job '${env.JOB_NAME} #${env.BUILD_NUMBER}'",
                    body: '${SCRIPT, template="groovy-text.template"}',
                    recipientProviders: [culprits(), brokenBuildSuspects(), brokenTestsSuspects()]
        }
        unstable {
            echo 'This will run only if the run was marked as unstable'
        }
        changed {
            echo 'This will run only if the state of the Pipeline has changed'
            echo 'For example, if the Pipeline was previously failing but is now successful'
        }
    }
}
