// Pull requests run tests and checks only. On main, a change under pricing/
// builds one image and promotes its digest from staging to production after a
// human approval. Setting RELEASE_RECORD redeploys an existing release without
// building, which is how rollback and recovery run.

// Applies one release record with Ansible on the delivery agent.
def deploy(String record, String label) {
    withCredentials([sshUserPrivateKey(credentialsId: 'delivery-ssh', keyFileVariable: 'SSH_KEY')]) {
        withEnv(["RECORD=${record}", "LABEL=${label}"]) {
            sh '''#!/bin/bash
                set -euo pipefail
                mkdir -p reports
                export ANSIBLE_COLLECTIONS_PATH="$WORKSPACE/.collections"
                "$TOOLS/ansible-galaxy" collection install -r ansible/requirements.yml -p "$ANSIBLE_COLLECTIONS_PATH"
                "$TOOLS/ansible-playbook" -i ansible/inventory.ini ansible/deploy.yml --syntax-check
                echo "deploy start: $(date -u +%FT%TZ) $RECORD"
                "$TOOLS/ansible-playbook" -i ansible/inventory.ini ansible/deploy.yml \
                    --private-key "$SSH_KEY" -e "@$RECORD" | tee "reports/$LABEL.txt"
                echo "deploy end: $(date -u +%FT%TZ) $RECORD"
            '''
        }
    }
}

// Prints the public behavior of a release as evidence; Ansible asserts it.
def smoke(String record) {
    withEnv(["RECORD=${record}"]) {
        sh '''#!/bin/bash
            set -euo pipefail
            URL=$(sed -n 's/^public_url: //p' "$RECORD")
            curl -fsS "$URL/"; curl -fsS "$URL/health"; curl -fsS "$URL/price?quantity=3"
            test "$(curl -s -o /dev/null -w '%{http_code}' "$URL/price?quantity=0")" = 400
            echo "invalid quantity returned 400"
        '''
    }
}

pipeline {
    agent none

    options {
        disableConcurrentBuilds()
        skipDefaultCheckout()
    }

    parameters {
        string(name: 'RELEASE_RECORD', defaultValue: '', description: 'Redeploy this record without building, for example releases/v1-production.yml.')
        string(name: 'CONFIG_REF', defaultValue: '', description: 'Commit whose ansible/ directory to use. Empty uses this build\'s commit. Production accepts only commits on main.')
    }

    environment {
        IMAGE = 'git.pollefeys.dev/seatbacktrivia/pricing'
        TOOLS = '/opt/delivery/bin'
        TRIVY_CACHE_DIR = '/home/jenkins/agent/trivy-cache'
    }

    stages {
        stage('Product tests') {
            agent { label 'built-in' }
            when { expression { !params.RELEASE_RECORD } }
            steps {
                checkout scm
                sh 'node --version'
                sh 'npm --version'
                sh 'npm ci'
                sh 'npm test'
            }
        }

        stage('Pricing tests') {
            agent { label 'delivery' }
            when { expression { !params.RELEASE_RECORD } }
            steps {
                script {
                    env.RELEASE_COMMIT = checkout(scm).GIT_COMMIT
                }
                dir('pricing') {
                    sh '''
                        python3 -m venv .venv
                        . .venv/bin/activate
                        pip install --quiet --disable-pip-version-check -r requirements.txt
                        python -m py_compile app.py test_app.py
                        python -m unittest -v
                    '''
                }
            }
        }

        stage('Dependency and secret checks') {
            agent { label 'delivery' }
            when { expression { !params.RELEASE_RECORD } }
            steps {
                sh '''
                    mkdir -p reports
                    trivy --version
                    trivy fs --scanners secret --skip-dirs pricing/.venv --exit-code 1 --no-progress --output reports/secrets.txt . \
                        || { cat reports/secrets.txt; exit 1; }
                    "$TOOLS/pip-audit" --version
                    "$TOOLS/pip-audit" -r pricing/requirements.txt --no-deps --disable-pip --output reports/pip-audit.txt \
                        || { cat reports/pip-audit.txt; exit 1; }
                    cat reports/secrets.txt reports/pip-audit.txt
                '''
            }
        }

        stage('Select release') {
            agent { label 'delivery' }
            when { allOf { branch 'main'; expression { !params.RELEASE_RECORD } } }
            steps {
                script {
                    env.DELIVER = sh(returnStatus: true, script: 'git diff --quiet HEAD^1 HEAD -- pricing') != 0 ? 'true' : 'false'
                    echo "pricing/ changed: ${env.DELIVER}"
                }
            }
        }

        stage('Build image') {
            agent { label 'delivery' }
            when { environment name: 'DELIVER', value: 'true' }
            steps {
                sh 'DOCKER_BUILDKIT=0 docker build --build-arg APP_COMMIT="$RELEASE_COMMIT" -t "$IMAGE:$RELEASE_COMMIT" pricing'
            }
        }

        stage('Scan image') {
            agent { label 'delivery' }
            when { environment name: 'DELIVER', value: 'true' }
            steps {
                sh '''
                    trivy image --image-src docker --scanners vuln --severity HIGH,CRITICAL \
                        --exit-code 1 --no-progress --output reports/image.txt "$IMAGE:$RELEASE_COMMIT" \
                        || { cat reports/image.txt; exit 1; }
                    cat reports/image.txt
                    trivy version | tee reports/trivy-version.txt
                '''
            }
        }

        stage('Publish image') {
            agent { label 'delivery' }
            when { environment name: 'DELIVER', value: 'true' }
            steps {
                withCredentials([usernamePassword(credentialsId: 'registry-write', usernameVariable: 'REG_USER', passwordVariable: 'REG_TOKEN')]) {
                    sh '''#!/bin/bash
                        set -euo pipefail
                        export DOCKER_CONFIG=$(mktemp -d)
                        trap 'rm -rf "$DOCKER_CONFIG"' EXIT
                        printf '%s' "$REG_TOKEN" | docker login "${IMAGE%%/*}" -u "$REG_USER" --password-stdin
                        docker push "$IMAGE:$RELEASE_COMMIT"
                        docker pull "$IMAGE:$RELEASE_COMMIT"
                        DIGEST=$(docker image inspect "$IMAGE:$RELEASE_COMMIT" --format '{{index .RepoDigests 0}}')
                        VERSION=$(sed -n 's/^VERSION = "\\(.*\\)"/\\1/p' pricing/app.py)
                        UNIT=$(sed -n 's/^UNIT_PRICE = //p' pricing/app.py)
                        for TARGET in staging production; do
                            HOST=app; [ "$TARGET" = staging ] && HOST=staging
                            cat > "releases/$VERSION-$TARGET.yml" <<EOF
target_env: $TARGET
release_image: $DIGEST
expected_version: $VERSION
expected_commit: $RELEASE_COMMIT
expected_total: $((UNIT * 3))
public_url: https://$HOST.pollefeys.dev
proxy_network: gitea_gitea-net
EOF
                        done
                        echo "$VERSION" > reports/version.txt
                        cat "releases/$VERSION-staging.yml"
                    '''
                }
                stash name: 'release', includes: 'releases/*.yml,reports/version.txt'
            }
        }

        stage('Deploy staging') {
            agent { label 'delivery' }
            when { environment name: 'DELIVER', value: 'true' }
            steps {
                unstash 'release'
                script {
                    def version = readFile('reports/version.txt').trim()
                    deploy("releases/${version}-staging.yml", 'staging-first-run')
                    // An unchanged rerun must report no changes.
                    deploy("releases/${version}-staging.yml", 'staging-second-run')
                    sh 'grep -E "changed=0 +unreachable=0 +failed=0" reports/staging-second-run.txt'
                    smoke("releases/${version}-staging.yml")
                }
            }
        }

        stage('Redeploy selected record') {
            agent { label 'delivery' }
            when { expression { params.RELEASE_RECORD && !params.RELEASE_RECORD.contains('production') } }
            steps {
                checkout scm
                sh '''
                    if [ -n "$CONFIG_REF" ]; then
                        git fetch --quiet "$(git remote get-url origin)" '+refs/heads/*:refs/remotes/all/*'
                        git checkout "$CONFIG_REF" -- ansible
                    fi
                '''
                script {
                    deploy(params.RELEASE_RECORD, 'redeploy')
                    smoke(params.RELEASE_RECORD)
                }
            }
        }

        stage('Production approval') {
            when {
                anyOf {
                    environment name: 'DELIVER', value: 'true'
                    expression { params.RELEASE_RECORD?.contains('production') }
                }
            }
            steps {
                script {
                    def target = params.RELEASE_RECORD ?: 'the release built by this run'
                    timeout(time: 30, unit: 'MINUTES') {
                        env.APPROVER = input(
                            message: "Deploy ${target} to production? Commit ${env.RELEASE_COMMIT ?: 'see record'}, build ${env.BUILD_NUMBER}. Check the image digest, scan result, and staging result in this run first.",
                            ok: 'Approve production',
                            submitter: 'natalie,cedric',
                            submitterParameter: 'APPROVER'
                        )
                    }
                    echo "Approved by ${env.APPROVER}"
                }
            }
        }

        stage('Deploy production') {
            agent { label 'delivery' }
            when {
                anyOf {
                    environment name: 'DELIVER', value: 'true'
                    expression { params.RELEASE_RECORD?.contains('production') }
                }
            }
            steps {
                script {
                    def record = params.RELEASE_RECORD
                    if (record) {
                        checkout scm
                        // Production uses only reviewed configuration from main.
                        sh '''
                            if [ -n "$CONFIG_REF" ]; then
                                git merge-base --is-ancestor "$CONFIG_REF" HEAD
                                git checkout "$CONFIG_REF" -- ansible
                            fi
                        '''
                    } else {
                        unstash 'release'
                        record = "releases/${readFile('reports/version.txt').trim()}-production.yml"
                    }
                    withEnv(["RECORD=${record}"]) {
                        sh 'mkdir -p reports; echo "approver=$APPROVER time=$(date -u +%FT%TZ) record=$RECORD" | tee reports/approval.txt'
                    }
                    deploy(record, 'production')
                    smoke(record)
                }
            }
        }
    }

    post {
        always {
            node('delivery') {
                archiveArtifacts artifacts: 'reports/**,releases/*.yml', allowEmptyArchive: true
            }
        }
    }
}
