pipeline {
    agent { label 'chapter6-trusted' }
    options {
        skipDefaultCheckout()
        disableConcurrentBuilds()
        timeout(time: 60, unit: 'MINUTES')
    }
    environment {
        IMAGE = 'git.sespinal590.dev/group10-startup/pricing'
        ANSIBLE_HOST_KEY_CHECKING = 'True'
    }
    stages {
        stage('Checkout and test') {
            steps {
                deleteDir()
                checkout scm
                sh 'bash secure-delivery/delivery.sh test'
            }
        }
        stage('Dependency, secret, and image gates') {
            steps { sh 'bash secure-delivery/delivery.sh scan' }
        }
        stage('Publish scanned image') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'chapter6-registry-write', usernameVariable: 'REG_USER', passwordVariable: 'REG_TOKEN')]) {
                    sh 'bash secure-delivery/delivery.sh publish'
                }
            }
        }
        stage('Deploy and verify staging') {
            steps { script { deployPricing('staging') } }
        }
        stage('Production approval') {
            steps {
                script {
                    if (!env.CHAPTER6_APPROVERS?.trim()) {
                        error('Configure CHAPTER6_APPROVERS on the restricted release job')
                    }
                    def digest = readFile('evidence/digest.txt').trim()
                    def revision = readFile('evidence/source.txt').trim()
                    def approver = timeout(time: 20, unit: 'MINUTES') {
                        input message: "Promote ${revision} / ${digest}? Scans, staging HTTPS checks and Ansible idempotence passed.",
                              submitter: env.CHAPTER6_APPROVERS, submitterParameter: 'APPROVER'
                    }
                    writeFile file: 'evidence/approval.txt', text: "Approved by ${approver}\n"
                    sh 'date -u +%FT%TZ >> evidence/approval.txt'
                }
            }
        }
        stage('Deploy and verify production') {
            steps { script { deployPricing('production') } }
        }
    }
    post {
        always { archiveArtifacts artifacts: 'evidence/*', allowEmptyArchive: true }
    }
}
def deployPricing(String target) {
    withEnv(["TARGET_ENV=${target}"]) {
        withCredentials([sshUserPrivateKey(credentialsId: 'chapter6-deploy-ssh', keyFileVariable: 'DEPLOY_KEY', usernameVariable: 'DEPLOY_USER'),
                         file(credentialsId: 'chapter6-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')]) {
            sh 'bash secure-delivery/delivery.sh deploy'
        }
    }
}
