import com.sonymusic.ECRImage
import com.sonymusic.Utils

def call(Map args = [:]) {
    def params = Utils.validateParams('datadogSoftwareCatalogValidate', args, [
        repositoryPath: [type: String, required: false, defaultValue: './'],
        servicePath: [type: String, required: false, defaultValue: ''],
        datadogToolsImage: [type: String, required: false, defaultValue: '086679231553.dkr.ecr.us-east-1.amazonaws.com/datadog-tools:latest'],
        serviceDefinitionFilePath: [type: String, required: false, defaultValue: '']
    ])

    ECRImage datadogToolsImage = ECRImage.fromString(params.datadogToolsImage)

    def serviceDefinitionFile = ''
    if (params.serviceDefinitionFilePath?.trim()) {
        serviceDefinitionFile = "--entity-definition-file-path '${params.serviceDefinitionFilePath}'"
    }

    def servicePathFlag = "--entity-path \"${params.servicePath}\""

    // Role session name must be <= 64 characters, so truncate if necessary
    def roleSessionName = env.BUILD_TAG?.length() > 64 ? env.BUILD_TAG[-64..-1] : env.BUILD_TAG

    // Unset AWS_PROFILE if set because withAWS will attempt to look up the profile from the Jenkins controller
    withEnv(["AWS_PROFILE="]) {
        withAWS(roleAccount: '086679231553', role: 'shared-datadog-software-catalog-role', roleSessionName: roleSessionName, useNode: true) {
            withEcr(registries: [[accountId: datadogToolsImage.accountId, region: datadogToolsImage.region]]) {
                sh """
                    docker run \
                        --network host \
                        --rm \
                        --pull always \
                        -v \"${params.repositoryPath}:/var/app/repository\" \
                        -e Environment=shared \
                        -e AWS_ACCESS_KEY_ID \
                        -e AWS_SECRET_ACCESS_KEY \
                        -e AWS_SESSION_TOKEN \
                        ${params.datadogToolsImage} \
                        software-catalog validate-entity \
                        --repository-path /var/app/repository \
                        ${servicePathFlag} \
                        ${serviceDefinitionFile}
                """
            }
        }
    }
}
