pipeline {
    agent {
        docker {
            image "getsentry/sentry-cli"
            args "--entrypoint="
        }
    }

    environment {
        projectDir = "${env.project_name}_${env.BUILD_ID}" 
    }

    stages {

        stage("Clone repository") {
            steps {
                checkout scm: 
                    [
                        $class: 'GitSCM', 
                        userRemoteConfigs: [[url: env.repository_url, credentialsId: 'jenkins-forge-ssh']], 
                        branches: [[name: env.ref]],
                        extensions: [
                            [$class: 'RelativeTargetDirectory', relativeTargetDir: env.projectDir ],
                            [$class: 'CloneOption', noTags: false, shallow: false, depth: 0, reference: ''],
                            [$class: 'WipeWorkspace' ]
                        ]
                    ], 
                    changelog: false, 
                    poll: false
            }
        }


        stage('Create sentry release') {
            steps {
                dir(env.projectDir) {
                    withCredentials([
                        string(credentialsId: 'sentry-url', variable: 'SENTRY_URL'),
                        string(credentialsId: 'sentry-release-auth-token', variable: 'SENTRY_AUTH_TOKEN')
                    ]) {
                        sh '''
                        SENTRY_CMD="sentry-cli --auth-token \"${SENTRY_AUTH_TOKEN}\" --url \"${SENTRY_URL}\""
                        PROJECT_VERSION=$(sentry-cli releases propose-version)
                        
                        $SENTRY_CMD \
                            releases \
                            --org "${sentry_org}" \
                            new \
                            -p "${sentry_project}" ${PROJECT_VERSION}

                        ( 
                            $SENTRY_CMD \
                                releases \
                                --org "${sentry_org}" \
                                set-commits --local \
                                ${PROJECT_VERSION} || exit 0
                        )

                         $SENTRY_CMD \
                            releases \
                            --org "${sentry_org}" \
                            finalize \
                            ${PROJECT_VERSION}
                        '''
                    }
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}