// Scrap-Web pipeline: Chapter 4 CI checks + Chapter 6 secure delivery.
//
// Trust boundary:
//  * Every build (branches and pull requests) runs the Chapter 4 checks on the
//    controller's built-in node. No credentials, no Docker socket.
//  * Delivery stages run only for trusted branches, on the 'delivery' agent,
//    which holds the Docker socket and the registry/deploy credentials.
//    TODO before submission: remove the feature branch from TRUSTED_BRANCH so
//    only reviewed code on main can deliver.

def TRUSTED_BRANCH = 'main'

pipeline {
    agent none

    options {
        skipDefaultCheckout()
        disableConcurrentBuilds()          // no competing releases
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '50'))
    }

    environment {
        REGISTRY = 'git.ssw590-08.me'
        IMAGE    = 'git.ssw590-08.me/ssw-590-08/pricing'
    }

    stages {
        // ---------------- Chapter 4 CI (all builds, controller) ----------------
        stage('CI checks') {
            agent { label 'built-in' }
            steps {
                checkout scm
                sh 'git rev-parse HEAD'
                sh 'python3 --version'
                sh 'python3 -m py_compile pricing.py tests/test_pricing.py'
                sh 'python3 -m unittest discover -s tests -v'
            }
        }

        // ---------------- Chapter 6 delivery (trusted branches, agent) ---------
        stage('Delivery') {
            when { beforeAgent true; branch pattern: TRUSTED_BRANCH, comparator: 'REGEXP' }
            agent { label 'delivery' }
            stages {
                stage('Checkout') {
                    steps {
                        checkout scm
                        script {
                            env.APP_COMMIT = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
                            env.IMAGE_TAG  = "${env.IMAGE}:${env.APP_COMMIT}"
                        }
                        echo "Source commit: ${env.APP_COMMIT}"
                    }
                }

                stage('Unit tests') {
                    steps {
                        dir('pricing') {
                            sh '''
                                python3 -m venv .venv
                                .venv/bin/pip install -q --require-hashes -r requirements.txt
                                .venv/bin/python -m py_compile app.py test_app.py
                                .venv/bin/python -m unittest -v
                            '''
                        }
                    }
                }

                // 6.4.5 (kholmes): dependency + secret checks on the source.
                stage('Security scan: source') {
                    steps {
                        sh '''
                            if [ -x security/scan.sh ]; then
                                security/scan.sh source
                            else
                                echo "security/scan.sh not added yet (6.4.5)"
                            fi
                        '''
                    }
                }

                stage('Build image') {
                    steps {
                        dir('pricing') {
                            sh 'docker build --build-arg APP_COMMIT="$APP_COMMIT" -t "$IMAGE_TAG" .'
                        }
                    }
                }

                // 6.4.5 (kholmes): image vulnerability scan before publishing.
                stage('Security scan: image') {
                    steps {
                        sh '''
                            if [ -x security/scan.sh ]; then
                                security/scan.sh image "$IMAGE_TAG"
                            else
                                echo "security/scan.sh not added yet (6.4.5)"
                            fi
                        '''
                    }
                }

                stage('Publish') {
                    steps {
                        withCredentials([usernamePassword(credentialsId: 'gitea-registry-push',
                                                          usernameVariable: 'REG_USER',
                                                          passwordVariable: 'REG_TOKEN')]) {
                            // Push, then delete the local copy and pull it back from the
                            // registry, so the recorded digest is the registry's, not a local ID.
                            sh '''
                                printf '%s' "$REG_TOKEN" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin
                                docker push "$IMAGE_TAG"
                                docker image rm "$IMAGE_TAG"
                                docker pull "$IMAGE_TAG"
                                docker logout "$REGISTRY"
                                docker image inspect "$IMAGE_TAG" --format '{{index .RepoDigests 0}}' > image-digest.txt
                                echo "Published: $(cat image-digest.txt)"
                            '''
                        }
                        script { env.IMAGE_DIGEST = readFile('image-digest.txt').trim() }
                        writeFile file: 'build-record.txt', text: """source_commit: ${env.APP_COMMIT}
image_tag: ${env.IMAGE_TAG}
image_digest: ${env.IMAGE_DIGEST}
jenkins_build: ${env.BUILD_URL}
"""
                        archiveArtifacts artifacts: 'image-digest.txt, build-record.txt', fingerprint: true
                    }
                }

                // 6.4.6: deploy the digest just published to staging with Ansible,
                // then rerun unchanged and require changed=0 (idempotence).
                stage('Deploy staging') {
                    steps {
                        script {
                            // Expected behaviour comes from the source, not from config.
                            def version = sh(script: "sed -n 's/^VERSION = \"\\(.*\\)\"/\\1/p' pricing/app.py", returnStdout: true).trim()
                            def unit    = sh(script: "sed -n 's/^UNIT_PRICE = //p' pricing/app.py", returnStdout: true).trim()
                            env.APP_VERSION = version
                            writeFile file: "release-${version}-staging.yml", text: """target_env: staging
release_image: ${env.IMAGE_DIGEST}
expected_version: ${version}
expected_commit: ${env.APP_COMMIT}
expected_total: ${3 * (unit as Integer)}
public_url: https://staging.ssw590-08.me
proxy_network: gitea-net
"""
                        }
                        archiveArtifacts artifacts: "release-${env.APP_VERSION}-staging.yml", fingerprint: true
                        withCredentials([sshUserPrivateKey(credentialsId: 'deploy-ssh', keyFileVariable: 'DEPLOY_KEY')]) {
                            sh '''
                                export PATH=/opt/ansible-venv/bin:$PATH
                                ansible-playbook -i ansible/inventory.ini ansible/deploy.yml --syntax-check
                                ansible-playbook -i ansible/inventory.ini ansible/deploy.yml \
                                  --private-key "$DEPLOY_KEY" -e @release-$APP_VERSION-staging.yml
                            '''
                        }
                    }
                }

                stage('Staging idempotence') {
                    steps {
                        withCredentials([sshUserPrivateKey(credentialsId: 'deploy-ssh', keyFileVariable: 'DEPLOY_KEY')]) {
                            sh '''
                                export PATH=/opt/ansible-venv/bin:$PATH
                                ansible-playbook -i ansible/inventory.ini ansible/deploy.yml \
                                  --private-key "$DEPLOY_KEY" -e @release-$APP_VERSION-staging.yml | tee rerun.log
                                grep -E 'startup +: .*changed=0 +unreachable=0 +failed=0' rerun.log \
                                  || { echo "Second run changed something: not idempotent"; exit 1; }
                            '''
                        }
                    }
                }


                // 6.4.7 (kholmes): approval + production deploy.
                stage('Approve and deploy production') {
                    steps { echo 'Not implemented yet (6.4.7).' }
                }
            }
        }
    }

    post {
        success { echo 'All stages passed.' }
        failure { echo 'A stage failed: see the stage view for which one.' }
    }
}
