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

@Field DEFAULT_AWS_REGION = 'us-east-1'
@Field DISTRIBUTIONS_BY_ENV = [
    qa: ['E1TQKM1RJXX2MF', 'E1V2KPLK0JZWXL'],
    uat: ['E1J2RABVXTA04A'],
    prod: ['E3U24DC9WT11IH', 'E2JV6Y8XZK7U5C']
]

def call(Map args) {
    def params = Utils.validateParams('cdnInvalidate', args, [
        appName: [type: String, required: true],
        env: [type: String, required: true],
        distributions: [type: List, itemType: String, required: false],
        awsRegion: [type: String, required: false, defaultValue: DEFAULT_AWS_REGION],
        waitForCompletion: [type: Boolean, required: false, defaultValue: false]
    ])

    def distributions = params.distributions ?: DISTRIBUTIONS_BY_ENV[params.env] ?: [];
    assert distributions: "cdnInvalidate: No distributions defined for the \"${params.env}\" environment."

    def paths = [
        "/${params.appName}/*.html",
        "/${params.appName}/favicon.*",
        // frontend-workstation
        "/${params.appName}/main.dml.*",
        "/${params.appName}/dml.*",
        "/${params.appName}/manifest*",

        // universal links
        "/${params.appName}/.well-known/*"
    ];

    withAWS(region: params.awsRegion, credentials: 'cdn-deploy') {
        for(int i = 0; i < distributions.size(); i++) {
            def distribution = distributions[i]

            cfInvalidate(
                distribution: distribution, 
                paths: paths, 
                waitForCompletion: params.waitForCompletion
            )
        }

        invalidateCaches(params.appName, params.env, params.awsRegion)
    }
}

def invalidateCaches(String appName, String env, String awsRegion){
    dir('cdnInvalidate') {
        checkout([
            $class: 'GitSCM', 
            branches: [[name: '*/master']], 
            doGenerateSubmoduleConfigurations: false, 
            extensions: [], 
            submoduleCfg: [], 
            userRemoteConfigs: [[
                credentialsId: '577cbc72-7d9e-4eba-924c-ecbbe6de9805',
                url: "git@github.com:theorchard/python-deployment-utils.git"
            ]]
        ])

        dir('cloudfront'){
            withEnv([
                "AWS_DEFAULT_REGION=${awsRegion}",
                "APP_NAME=${appName}",
                "ENV=${env}"
            ]){
                sh """
                    echo "AWS_DEFAULT_REGION is \${AWS_DEFAULT_REGION}"
                    echo "APP_NAME is \${APP_NAME}"

                    set +x
                    python3 -m venv venv
                    . ./venv/bin/activate
                    pip install -r requirements.txt
                    set -x
                    python3 -u invalidate_caches.py
                """
            }
        }
    }
}
