@Library('flexo-libs') _

currentBuild.displayName = "#${BUILD_ID}: Building ECR Containers"
currentBuild.description = """
  Builds Fluent Bit & Nginx Docker containers for ECR. Deploys to multiple regions and/or accounts. Optionally reloads an ECS service.
  Deployment to dev happens automatically on any push to master branch. Deployment to dev from other branches requires manual build.
  Deployment to production is only possible from master branch and only happens when requested.
  To reload a service, add the service name (usually 'syslog') to the RELOAD_SERVICE parameter.
  Set the service name as the default for the RELOAD_SERVICE parameter in the Jenkinsfile to trigger automatic service reload during deploys.
"""

pipeline {
  agent any

  // Account IDs must be corrected to match your accounts. Add more regions below if you deploy to multiple regions.
  parameters {
    string(name: 'PROD_ACCT', defaultValue: '277437172290', description: 'Production or staging account ID.')

    booleanParam(name: 'DEPLOY_PROD', defaultValue: false,
      description: 'Deploy this build to prod.')
    string(name: 'RELOAD_SERVICE', defaultValue: 'InfobloxSyslog',
      description: 'Optionally reload ECS service(s) in the defined region(s). ie. syslog to reload fluentbit-syslog')
    string(name: 'REGIONS', defaultValue: 'us-west-2',
      description: 'Regions where the ECS and ECR resources reside. Separate additional regions with spaces.')
    string(name: 'VERSION', defaultValue: '2.10.1', // '2.10.1' - pin this for prod.
      description: 'Which version of the public.ecr.aws/aws-observability/aws-for-fluent-bit container to use.')
  }

  environment {
    BUILD_DATE  = sh(script: "date -u +%Y-%m-%dT%H:%M:%SZ", returnStdout: true).trim()
    ROLE_NAME   = "fluentbit-syslog-jenkins-ecs-ecr" // matches cfn-jenkins.yml
    NGINX_REPO  = "twitch-fluentbit-syslog-nginx"
    FLUENT_REPO = "twitch-fluentbit-syslog"
  }

  stages {
    stage('build') {
      steps {
        sh """
        docker build --file docker/Dockerfile.fluentbit \
          --build-arg COMMIT=${GIT_COMMIT} \
          --build-arg BUILD_URL=${BUILD_URL} \
          --build-arg URL=${GIT_URL} \
          --build-arg BUILD_DATE=${BUILD_DATE} \
          --tag ${FLUENT_REPO}:${GIT_COMMIT} .
        docker build --file docker/Dockerfile.nginx \
          --build-arg COMMIT=${GIT_COMMIT} \
          --build-arg BUILD_URL=${BUILD_URL} \
          --build-arg URL=${GIT_URL} \
          --build-arg BUILD_DATE=${BUILD_DATE} \
          --tag ${NGINX_REPO}:${GIT_COMMIT} .
        """
      }
    }


    stage('deploy_prod') {
      // Only deploy prod from master _and_ only when asked to.
      when { allOf {
        branch 'master'
        expression { return params.DEPLOY_PROD }
      }}
      steps { script { deploy_ecr(PROD_ACCT, "${REGIONS}".split("[\\s,]+")) } }
    }

    stage('reload_prod_service') {
      when { allOf {
        branch 'master'
        expression { return params.DEPLOY_PROD }
        expression { return params.RELOAD_SERVICE != "" }
      }}
      steps { script { reload_ecs(PROD_ACCT, "${REGIONS}".split("[\\s,]+")) } }
    }
  }
}

def reload_ecs(toAcct,regions) {
  for (int i=0; i<regions.size();i++) {
    withAWS(role:ROLE_NAME, roleAccount:toAcct, region: regions[i]) {
      sh """
      aws ecs update-service --force-new-deployment --cluster=fluentbit-${RELOAD_SERVICE}-Cluster --service=fluentbit-${RELOAD_SERVICE}
      """
    }
  }
}

// Create ECR repos and upload our containers to each provided region.
def deploy_ecr(toAcct,regions) {
  for (int i=0; i<regions.size();i++) {
    withAWS(role:ROLE_NAME, roleAccount:toAcct, region: regions[i]) {
      sh """
      aws --region ${regions[i]} ecr create-repository --repository-name ${FLUENT_REPO} || true
      aws --region ${regions[i]} ecr create-repository --repository-name ${NGINX_REPO} || true
      eval \$(aws ecr get-login --no-include-email --region ${regions[i]})
      docker tag ${FLUENT_REPO}:${GIT_COMMIT} "${toAcct}.dkr.ecr.${regions[i]}.amazonaws.com/${FLUENT_REPO}:latest"
      docker tag ${NGINX_REPO}:${GIT_COMMIT} "${toAcct}.dkr.ecr.${regions[i]}.amazonaws.com/${NGINX_REPO}:latest"
      docker push ${toAcct}.dkr.ecr.${regions[i]}.amazonaws.com/${FLUENT_REPO}:latest
      docker push ${toAcct}.dkr.ecr.${regions[i]}.amazonaws.com/${NGINX_REPO}:latest
      """
    }
  }
}
