import groovy.transform.Field
import com.sonymusic.Utils

@Field DEFAULT_AWS_REGION = 'us-east-1'

// AWS s3Upload documentation: https://plugins.jenkins.io/pipeline-aws/#plugin-content-s3upload

def call(Map args) {
    def params = Utils.validateParams('suiteAppPublish', args, [
        env: [type: String, required: true],
        appName: [type: String, required: true],
        awsRegion: [type: String, required: false, defaultValue: DEFAULT_AWS_REGION],
        awsDeploymentRoleName: [type: String, required: false, defaultValue: 'prod-cdn-deploy-role'],
        awsDeploymentRoleAccountId: [type: String, required: false, defaultValue: '437795906767'],
        bucket: [type: String, required: false],
        subpath: [type: String, required: false],
        noCacheExtraPatterns: [type: String, required: false, defaultValue: '']
    ])

    def bucket = params.bucket ?: "${params.env}-orcd-cdn"
    def path = params.subpath ? "${params.appName}/${params.subpath}": params.appName

    def defaultNoCachePatterns = 'index*.html,dml.json,manifest.json'
    def normalizedExtraPatterns = params.noCacheExtraPatterns?.
        split(',')?.
        collect { it.trim() }?.
        findAll { it }?.
        join(',')
    def noCachePatterns = normalizedExtraPatterns ?
        "${defaultNoCachePatterns},${normalizedExtraPatterns}" :
        defaultNoCachePatterns

    withAWS(region: params.awsRegion, role: params.awsDeploymentRoleName, roleAccount: params.awsDeploymentRoleAccountId, roleSessionName: params.awsDeploymentRoleName, useNode: true){
        s3Upload(
            bucket: bucket,
            path: path,
            workingDir: 'build',
            includePathPattern: '**/*',
            excludePathPattern: noCachePatterns,
            cacheControl:'public,max-age=31536000'
        )

        s3Upload(
            bucket: bucket,
            path: path,
            workingDir: 'build',
            includePathPattern: noCachePatterns,
            cacheControl:'no-store'
        )
    }
}
