pipeline {
  agent {
    label 'linux-agents'
  }

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

  environment {
    AWS_PROFILE     = "gdb-artistapp-prod"
    DISTRIBUTION_ID = "E1E28PA8OX3KYK"
  }

  stages {
    stage ('Upload') {
      when {
        branch 'master'
      }
      steps {
        sh "aws s3 sync --no-progress src/ s3://sma.stream/"
        sh """aws s3 cp \
          s3://sma.stream/.well-known/apple-app-site-association \
          s3://sma.stream/.well-known/apple-app-site-association \
          --content-type application/json \
          --metadata-directive REPLACE
        """
        sh """aws s3 cp \
          s3://sma.stream/.well-known/assetlinks.json \
          s3://sma.stream/.well-known/assetlinks.json \
          --content-type application/json \
          --metadata-directive REPLACE
        """
      }
    }

    // TODO: move invalidation part to Lambda function
    stage ('Update') {
      when {
        branch 'master'
      }
      environment {
        INVALIDATION_ID = sh(label: 'create-invalidation', returnStdout: true, script: """
                            aws cloudfront create-invalidation \
                              --distribution-id ${env.DISTRIBUTION_ID} \
                              --paths "/index.html" "/error.html" \
                                "/.well-known/apple-app-site-association" \
                                "/.well-known/assetlinks.json" \
                              | jq -r '.Invalidation.Id'
                          """).trim()
      }
      steps {
        sh label: 'invalidation-completed', script: """
          aws cloudfront wait invalidation-completed \
            --distribution-id ${env.DISTRIBUTION_ID} \
            --id ${env.INVALIDATION_ID}
        """
      }
    }
  }
}
