pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        string(name: 'PROJECT', description: 'The path to the Terraform project in terraform-infra')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@master"
            }
        }
        stage('Fix Terraform State') {
            environment {
                ACCOUNT_ID = "437795906767"
                // Reuse state-file-fixer role and secret
                ROLE = "prod-terraform-state-file-fixer-role"
                SSH_KEY_SECRET = "prod/terraform-state-file-fixer/GITHUB_SSH_KEY"
            }
            steps {
                dir('terraform') {
                    checkout([
                        $class: 'GitSCM',
                        branches: [[name: "master"]],
                        userRemoteConfigs: [
                            [
                                credentialsId: '577cbc72-7d9e-4eba-924c-ecbbe6de9805',
                                url: "git@github.com:theorchard/terraform-infra.git"
                            ]
                        ]]
                    )
                    // Ensure Docker container has permissions to run terraform commands
                    sh "chmod -R a=rwx '${params.PROJECT}'"
                    script {
                        currentBuild.description = "${params.PROJECT}"
                    }
                }
                dir('replace-snowflake-provider') {
                    withEcr {
                        withAWS(roleAccount: env.ACCOUNT_ID, role: env.ROLE, roleSessionName: env.BUILD_TAG, useNode: true) {
                            withSecrets(secrets: [
                                [id: env.SSH_KEY_SECRET, environmentVariable: 'GITHUB_SSH_KEY'],
                            ]) {
                                withEnv(["TERRAFORM_PROJECT=../terraform/${params.PROJECT}"]) {
                                    sh 'docker compose run --rm --build replace-provider'
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}
