STRING SLACK_NOTIFICATIONS_CHANNEL = '#distro-build-alerts'

pipeline {
    agent any

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

    parameters {
        string(name: 'REPO_NAME', defaultValue: '', description: 'Name of the repository to update (e.g., ows-delivery-metadata)')
        string(name: 'PACKAGE_NAME', defaultValue: '', description: 'Optional package name to update')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@master"
            }
        }

        stage('Checkout Repository') {
            steps {
                script {
                    currentBuild.description = REPO_NAME
                }
                dir('update-lockfile') {
                    checkout([
                        $class: 'GitSCM',
                        branches: [[name: '*/master']],
                        userRemoteConfigs: [[
                            url: "git@github.com:theorchard/${REPO_NAME}.git",
                            credentialsId: 'OrchardCI Github Token'
                        ]]
                    ])
                }
            }
        }

        stage('Update Dependencies') {
            steps {
                dir('update-lockfile') {
                    withEcr {
                        sh "./update-deps.sh ${PACKAGE_NAME}"
                    }
                    withCredentials([string(credentialsId: 'OrchardCI Github Token', variable: 'GITHUB_TOKEN')]) {
                        sh './create-pr.sh'
                    }
                }
            }
        }
    }

    post {
        regression {
            script {
                slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
            }
        }
        fixed {
            script {
                slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
