// 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.
//
// Two kinds of run:
//  * Normal run (DEPLOY_RECORD empty): test, scan, build once, publish, deploy
//    staging, prove idempotence, human approval, promote the SAME digest.
//  * Redeploy run (DEPLOY_RECORD = a committed release record, e.g.
//    releases/v1-production.yml): no build; redeploys exactly that record with
//    this commit's Ansible files. Used for rollback and failed-deploy recovery.
//    Production redeploys need the same approval.

def TRUSTED_BRANCH = 'main'
// Jenkins user IDs allowed to approve production. Anonymous users cannot.
def APPROVERS = 'samahk,kaylah7'

def deployRecord(String record) {
    withCredentials([sshUserPrivateKey(credentialsId: 'deploy-ssh', keyFileVariable: 'DEPLOY_KEY')]) {
        withEnv(["RECORD=${record}"]) {
            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 @"$RECORD"
            '''
        }
    }
}

pipeline {
    agent none

    parameters {
        string(name: 'DEPLOY_RECORD', defaultValue: '',
               description: 'Leave EMPTY for a normal release. For rollback/recovery, the path of a committed release record, e.g. releases/v1-production.yml')
    }

    options {
        skipDefaultCheckout()
        disableConcurrentBuilds()          // no competing releases
        timeout(time: 60, 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'
                expression { (params.DEPLOY_RECORD ?: '').trim() == '' }
            }
            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: dependency and secret checks on the source. Fails closed:
                // a missing script, a scanner error, or a finding stops the run.
                stage('Security scan: source') {
                    steps { sh 'bash security/scan.sh source' }
                    post { always { archiveArtifacts artifacts: 'security-reports/**', allowEmptyArchive: true } }
                }

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

                // 6.4.5: image vulnerability scan before publishing. Fails closed.
                stage('Security scan: image') {
                    steps { sh 'bash security/scan.sh image "$IMAGE_TAG"' }
                    post { always { archiveArtifacts artifacts: 'security-reports/**', allowEmptyArchive: true } }
                }

                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.
                            env.APP_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.EXPECTED_TOTAL = "${3 * (unit as Integer)}"
                            writeFile file: "release-${env.APP_VERSION}-staging.yml", text: """target_env: staging
release_image: ${env.IMAGE_DIGEST}
expected_version: ${env.APP_VERSION}
expected_commit: ${env.APP_COMMIT}
expected_total: ${env.EXPECTED_TOTAL}
public_url: https://staging.ssw590-08.me
proxy_network: gitea-net
"""
                        }
                        archiveArtifacts artifacts: "release-${env.APP_VERSION}-staging.yml", fingerprint: true
                        deployRecord("release-${env.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: restricted human approval, then promote the SAME digest.
                stage('Approve production') {
                    steps {
                        script {
                            def scan = fileExists('security-reports/image-summary.txt') ?
                                readFile('security-reports/image-summary.txt').trim() : 'see security-reports'
                            // Only APPROVERS can approve; Abort or the timeout stops the run.
                            timeout(time: 30, unit: 'MINUTES') {
                                env.APPROVER = input(
                                    message: """Promote ${env.APP_VERSION} to production (https://app.ssw590-08.me)?
Source commit: ${env.APP_COMMIT}
Image digest:  ${env.IMAGE_DIGEST}
Security scans: source and image gates PASSED (fixable HIGH/CRITICAL block).
${scan}
Staging: deployed, HTTPS health/version/commit/total ${env.EXPECTED_TOTAL} passed, rerun changed=0.""",
                                    ok: 'Approve and deploy to production',
                                    submitter: APPROVERS,
                                    submitterParameter: 'APPROVER')
                            }
                            env.APPROVED_AT = sh(script: 'date -Is', returnStdout: true).trim()
                            echo "APPROVED by ${env.APPROVER} at ${env.APPROVED_AT}"
                        }
                    }
                }

                stage('Deploy production') {
                    steps {
                        // Same digest and commit as staging; only environment and URL change. No rebuild.
                        writeFile file: "release-${env.APP_VERSION}-production.yml", text: """target_env: production
release_image: ${env.IMAGE_DIGEST}
expected_version: ${env.APP_VERSION}
expected_commit: ${env.APP_COMMIT}
expected_total: ${env.EXPECTED_TOTAL}
public_url: https://app.ssw590-08.me
proxy_network: gitea-net
approved_by: ${env.APPROVER}
approved_at: ${env.APPROVED_AT}
"""
                        archiveArtifacts artifacts: "release-${env.APP_VERSION}-production.yml", fingerprint: true
                        deployRecord("release-${env.APP_VERSION}-production.yml")
                    }
                }
            }
        }

        // ---------------- Rollback / recovery: redeploy a committed record -----
        stage('Redeploy release record') {
            when {
                beforeAgent true
                branch pattern: TRUSTED_BRANCH, comparator: 'REGEXP'
                expression { (params.DEPLOY_RECORD ?: '').trim() != '' }
            }
            agent { label 'delivery' }
            stages {
                stage('Load record') {
                    steps {
                        checkout scm
                        script {
                            env.RECORD = params.DEPLOY_RECORD.trim()
                            if (!(env.RECORD ==~ /releases\/[A-Za-z0-9._-]+\.yml/) || !fileExists(env.RECORD)) {
                                error "No committed release record at ${env.RECORD}"
                            }
                            env.TARGET_ENV = sh(script: 'sed -n "s/^target_env: //p" "$RECORD"', returnStdout: true).trim()
                            env.CONFIG_COMMIT = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
                        }
                        echo "Redeploying ${env.RECORD} to ${env.TARGET_ENV} with configuration commit ${env.CONFIG_COMMIT}"
                        sh 'cat "$RECORD"'
                        archiveArtifacts artifacts: "${env.RECORD}", fingerprint: true
                    }
                }

                stage('Approve redeploy') {
                    when { environment name: 'TARGET_ENV', value: 'production' }
                    steps {
                        script {
                            timeout(time: 30, unit: 'MINUTES') {
                                env.APPROVER = input(
                                    message: "Redeploy ${env.RECORD} to PRODUCTION (configuration commit ${env.CONFIG_COMMIT})?",
                                    ok: 'Approve redeploy',
                                    submitter: APPROVERS,
                                    submitterParameter: 'APPROVER')
                            }
                            echo "APPROVED by ${env.APPROVER} at ${sh(script: 'date -Is', returnStdout: true).trim()}"
                        }
                    }
                }

                stage('Redeploy') {
                    steps {
                        sh 'echo "Redeploy start: $(date -Is)"'
                        deployRecord(env.RECORD)
                        sh 'echo "Redeploy verified: $(date -Is)"'
                    }
                }
            }
        }
    }

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