// A separate trusted delivery job loads this file from protected main.
// The existing multibranch PR job keeps its ordinary test-only Jenkinsfile.
pipeline {
    agent { label 'delivery-trusted' }
    options {
        skipDefaultCheckout()
        disableConcurrentBuilds()
        timeout(time: 60, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }
    parameters {
        choice(name: 'MODE', choices: ['release', 'blocked-test', 'blocked-secret', 'rollback-production', 'staging-failure', 'recover-staging'], description: 'Reviewed release or recovery operation')
        string(name: 'SOURCE_COMMIT', defaultValue: '', description: 'Optional full reviewed source commit already on main')
        string(name: 'RELEASE_RECORD', defaultValue: '', description: 'Reviewed delivery/releases/*.json for rollback or recovery')
        string(name: 'STAGING_FAILURE_CONFIG', defaultValue: '', description: 'Only for staging-failure. Full reviewed commit of the staging-only bad command template')
    }
    environment {
        PYTHONDONTWRITEBYTECODE = '1'
        TRIVY_CACHE_DIR = '/home/jenkins/agent/.cache/trivy'
    }
    stages {
        stage('Reviewed checkout') {
            steps {
                deleteDir()
                checkout scm
                script {
                    if (params.SOURCE_COMMIT) {
                        if (!(params.SOURCE_COMMIT ==~ /[0-9a-f]{40}/)) {
                            error('SOURCE_COMMIT must be a full Git commit')
                        }
                        withEnv(["RELEASE_SOURCE=${params.SOURCE_COMMIT}"]) {
                            sh 'git merge-base --is-ancestor "$RELEASE_SOURCE" origin/main && git checkout --detach "$RELEASE_SOURCE"'
                        }
                    }
                }
                sh 'git merge-base --is-ancestor HEAD origin/main'
                sh 'mkdir -p build/delivery/reports && git rev-parse HEAD > build/delivery/reports/source-commit.txt'
            }
        }
        stage('Unit tests') {
            steps {
                sh 'python3 -B -m unittest discover -s delivery/ci -p "test_controls.py" -v'
                script {
                    withEnv(["TEST_FAILURE=${params.MODE == 'blocked-test'}"]) {
                        sh 'sh delivery/ci/test-app.sh'
                    }
                }
            }
        }
        stage('Source security gates') {
            steps {
                script {
                    def fixture = params.MODE == 'blocked-secret' ? ' --fixture' : ''
                    sh "python3 delivery/ci/security.py source${fixture}"
                }
            }
        }
        stage('Build, scan, publish') {
            when { expression { params.MODE == 'release' } }
            steps {
                withCredentials([usernamePassword(credentialsId: 'delivery-registry-write', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_TOKEN')]) {
                    sh 'sh delivery/ci/publish.sh'
                }
            }
        }
        stage('Select release record') {
            steps {
                script {
                    if (params.MODE == 'release') {
                        env.SELECTED_RECORD = sh(script: "find build/delivery/releases -name '*-staging.json'", returnStdout: true).trim()
                    } else {
                        if (!(params.RELEASE_RECORD ==~ /delivery\/releases\/[a-zA-Z0-9._-]+\.json/)) {
                            error('Choose a committed delivery/releases/*.json record')
                        }
                        env.SELECTED_RECORD = params.RELEASE_RECORD
                        if (params.MODE == 'staging-failure') {
                            if (!(params.STAGING_FAILURE_CONFIG ==~ /[0-9a-f]{40}/)) {
                                error('Choose the full reviewed staging failure configuration commit')
                            }
                            withEnv(["FAILURE_CONFIG=${params.STAGING_FAILURE_CONFIG}"]) {
                                sh '''mkdir -p build/delivery/releases
python3 - <<'PY'
import json, os
from pathlib import Path
record = json.loads(Path(os.environ['SELECTED_RECORD']).read_text())
assert record['target_env'] == 'staging', 'Failure exercise requires staging'
record['configuration_commit'] = os.environ['FAILURE_CONFIG']
Path('build/delivery/releases/failure-staging.json').write_text(json.dumps(record, indent=2))
PY'''
                            }
                            env.SELECTED_RECORD = 'build/delivery/releases/failure-staging.json'
                        }
                    }
                }
                sh 'python3 delivery/ci/release.py verify "$SELECTED_RECORD"'
            }
        }
        stage('Staging deploy and unchanged rerun') {
            when { expression { params.MODE == 'release' || params.MODE == 'recover-staging' || params.MODE == 'staging-failure' } }
            steps {
                withCredentials([
                    sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
                    file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
                ]) {
                    sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" staging'
                    sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" staging rerun'
                }
            }
        }
        stage('Production approval') {
            when { expression { params.MODE == 'release' || params.MODE == 'rollback-production' } }
            steps {
                archiveArtifacts(artifacts: 'build/delivery/reports/**,build/delivery/releases/**', allowEmptyArchive: false)
                script {
                    if (params.MODE == 'release') {
                        env.SELECTED_RECORD = env.SELECTED_RECORD.replace('-staging.json', '-production.json')
                    }
                    sh 'python3 delivery/ci/release.py verify "$SELECTED_RECORD" --environment production'
                    def record = readFile(env.SELECTED_RECORD)
                    def approver
                    timeout(time: 20, unit: 'MINUTES') {
                        approver = input(message: "Approve production? Source, digest and target below. Review archived scan reports and staging console results.\n${record}", ok: 'Approve production', submitter: 'billy,vsun1', submitterParameter: 'APPROVER')
                    }
                    def approvedAt = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true).trim()
                    writeFile(file: 'build/delivery/reports/production-approval.txt', text: "Approver=${approver}\nDecision=approved\nUTC=${approvedAt}\n${record}\n")
                }
            }
        }
        stage('Production deploy and verification') {
            when { expression { params.MODE == 'release' || params.MODE == 'rollback-production' } }
            steps {
                withCredentials([
                    sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
                    file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
                ]) {
                    sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" production'
                }
            }
        }
    }
    post {
        always {
            archiveArtifacts(artifacts: 'build/delivery/reports/**,build/delivery/releases/**', excludes: '**/test-venv/**', allowEmptyArchive: true)
        }
    }
}
