pipeline {
  agent any

  parameters {
    choice(
      name: 'TARGET_REPOSITORY',
      choices: [
        'terraform-infra-core',
        'terraform-infra'
      ],
      description: 'The repository to run the dependabot for.'
    )

    string(
      name: 'PATH',
      defaultValue: 'dev',
      description: 'The relative path to the terraform configuration inside the repository'
    )

    string(
      name: 'SHARED_LIBRARIES_VERSION',
      defaultValue: 'master',
      description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, or Git revision.'
    )
  }

  stages {
    stage('Load Shared Libraries') {
      steps {
        library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
      }
    }
    stage('Build') {
      steps {
        sh script: 'cd bbabiy/python/dependabro && docker build -t dependabot .'
      }
    }
    stage('Run Terraform Modules Update') {
      steps {
        dir(params.TARGET_REPOSITORY) {
          checkout([
            $class: 'GitSCM',
            branches: [[name: '*/master']],
            doGenerateSubmoduleConfigurations: false,
            extensions: [],
            submoduleCfg: [],
            userRemoteConfigs: [
              [
                credentialsId: '577cbc72-7d9e-4eba-924c-ecbbe6de9805', // Replace with your credentials ID
                url: "git@github.com:theorchard/${params.TARGET_REPOSITORY}.git"
              ]
            ]
          ])

          withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')]) {
            sh script: """
              docker run \
                -e GITHUB_TOKEN \
                -v \$(pwd):/var/app/repo \
                dependabot \
                /var/app/repo/${params.PATH}
            """
          }
        }
      }
    }
    stage('Commit and Push Changes') {
      steps {
        dir(params.TARGET_REPOSITORY) {
          sshagent(['theorchard-ci-ssh-key']) {
            sh script: '''
              git status
            '''
          }
        }
      }
  }
  }
  post {
    always {
      cleanWs()
    }
  }
}
