String AWS_ACCOUNT_ID = '437795906767'
String QA_S3_ASSUME_ROLE = 'qa-spatial-asset-ingester-secrets-s3-assume-role'
String PROD_S3_ASSUME_ROLE = 'prod-spatial-asset-ingester-secrets-s3-assume-role'
String QA_ART_RELATIONS_DB_HOST = 'qa.db.qaorch.com'
String PROD_ART_RELATIONS_DB_HOST = 'ar-db.theorchard.com'

pipeline {
    agent any

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

    parameters {
        choice(
            name: 'ENVIRONMENT',
            choices: ['prod', 'qa'],
            description: 'Environment to run the spatial ingester against.'
        )
        stashedFile(
            name: 'BULK_SPATIAL_FILE',
            description: 'Optional bulk ingest file. Required headers: STEREO_UPC,STEREO_ISRC,SPATIAL_UPC,SPATIAL_ISRC.\nWhen set, this file input replaces the STEREO_UPC/STEREO_ISRC/SPATIAL_UPC/SPATIAL_ISRC options.'
        )
        string(
            name: 'STEREO_UPC',
            description: 'Stereo UPC'
        )
        string(
            name: 'STEREO_ISRC',
            description: 'Stereo ISRC.',
        )
        string(
            name: 'SPATIAL_UPC',
            description: 'Spatial UPC.',
        )
        string(
            name: 'SPATIAL_ISRC',
            description: 'Spatial ISRC.',
        )
    }

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

        stage('Ingest Spatial Audio') {
            steps {
                script {
                    S3_ASSUME_ROLE = "${params.ENVIRONMENT == "prod" ? PROD_S3_ASSUME_ROLE : QA_S3_ASSUME_ROLE}"

                    def fileUploaded = false
                    def volumeArg = ''
                    def filePath = ''
                    withFileParameter(name: 'BULK_SPATIAL_FILE', allowNoFile: true) {
                        def status = sh(
                            script: '''
                                if [ -n "$BULK_SPATIAL_FILE" ] && [ -s "$BULK_SPATIAL_FILE" ]; then
                                    cp "$BULK_SPATIAL_FILE" "$WORKSPACE/spatial_assets_file.csv"
                                    exit 0
                                else
                                    exit 1
                                fi
                            ''',
                            returnStatus: true
                        )

                        if (status == 0 && fileExists("${env.WORKSPACE}/spatial_assets_file.csv")) {
                            fileUploaded = true
                            filePath = '/var/app/spatial_assets_file.csv'
                            volumeArg = "--volume ${env.WORKSPACE}/spatial_assets_file.csv:${filePath}"
                        }
                    }

                    if (!fileUploaded && !(
                        params.STEREO_UPC?.trim()
                        && params.STEREO_ISRC?.trim()
                        && params.SPATIAL_UPC?.trim()
                        && params.SPATIAL_ISRC?.trim()
                    )) {
                        error "You must either upload a BULK_SPATIAL_FILE or provide values in STEREO_UPC, STEREO_ISRC, SPATIAL_UPC, and SPATIAL_ISRC."
                    }

                    if (!params.ENVIRONMENT?.trim()) {
                        error "ENVIRONMENT parameter is required."
                    }

                    def runDocker = {
                        withEcr {
                            withAWS(
                                roleAccount: AWS_ACCOUNT_ID,
                                role: S3_ASSUME_ROLE,
                                roleSessionName: env.BUILD_TAG,
                                useNode: true,
                                duration: 43200
                            ) {
                                withEnv([
                                    "ENVIRONMENT=${params.ENVIRONMENT}",
                                    "BULK_SPATIAL_FILE=${filePath}",
                                    "STEREO_UPC=${params.STEREO_UPC}",
                                    "STEREO_ISRC=${params.STEREO_ISRC}",
                                    "SPATIAL_UPC=${params.SPATIAL_UPC}",
                                    "SPATIAL_ISRC=${params.SPATIAL_ISRC}",
                                    "ART_RELATIONS_DB_HOST=${params.ENVIRONMENT == "prod" ? PROD_ART_RELATIONS_DB_HOST : QA_ART_RELATIONS_DB_HOST}",
                                    "ART_RELATIONS_DB_USER=spatial-asset-ingester",
                                ]) {
                                    dir('spatial-asset-ingester') {
                                        sh """
                                            docker compose run --build --rm \
                                                -e BULK_SPATIAL_FILE \
                                                -e STEREO_UPC \
                                                -e STEREO_ISRC \
                                                -e SPATIAL_UPC \
                                                -e SPATIAL_ISRC \
                                                -e ENVIRONMENT \
                                                -e ART_RELATIONS_DB_HOST \
                                                -e ART_RELATIONS_DB_USER \
                                                ${volumeArg} \
                                                app
                                        """
                                    }
                                }
                            }
                        }
                    }

                    if (fileUploaded) {
                        lock('spatial-asset-ingester-bulk') {
                            runDocker()
                        }
                    } else {
                        runDocker()
                    }
                }
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}
