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

def call(Map args = [:]) {
    def params = Utils.validateParams('airflowDeploy', args, [
        bucket: [type: String, required: true],
        environment: [type: String, required: true],
        gitCommit: [type: String, required: true],
        kmsKeyId: [type: String, required: true],
        serviceName: [type: String, required: true],
        airflowToolsImage: [type: String, required: false, defaultValue: '086679231553.dkr.ecr.us-east-1.amazonaws.com/airflow-tools:latest'],
        awsDeploymentRoleName: [type: String, required: false],
        awsDeploymentTargetAccountId: [type: String, required: false],
        bucketPrefix: [type: String, required: false, defaultValue: ''],
        dagsFolder: [type: String, required: false, defaultValue: './dags'],
        requirementsFile: [type: String, required: false, defaultValue: './requirements.txt'],
        rollback: [type: Boolean, required: false, defaultValue: false],
    ])

    ECRImage airflowToolsImage = ECRImage.fromString(params.airflowToolsImage)

    withEcr(registries: [[accountId: airflowToolsImage.accountId, region: airflowToolsImage.region]]) {
        if (args.awsDeploymentRoleName && args.awsDeploymentTargetAccountId) {
            withAWS(role: args.awsDeploymentRoleName, roleAccount: args.awsDeploymentTargetAccountId, roleSessionName: env.BUILD_TAG, useNode: true) {
                deploy(params)
            }
        } else {
            deploy(params)
        }
    }
}

private void deploy(params) {
    sh """
        docker run \\
            --rm \\
            --pull always \\
            -v "${params.dagsFolder}:/var/app/dags" \\
            -v "${params.requirementsFile}:/var/app/requirements.txt" \\
            -e AWS_ACCESS_KEY_ID \\
            -e AWS_SECRET_ACCESS_KEY \\
            -e AWS_SESSION_TOKEN \\
            ${params.airflowToolsImage} \\
            deploy \\
            --bucket ${params.bucket} \\
            --environment ${params.environment} \\
            --git-commit ${params.gitCommit} \\
            --kms-key-id ${params.kmsKeyId} \\
            --service-name ${params.serviceName} \\
            --bucket-prefix "${params.bucketPrefix}" \\
            ${params.rollback ? '--rollback' : '--no-rollback'}
    """
}
