/*
Config mandatory properties:
name
path

Optional properties:
slack_channel
aws_profile
*/
def call(body) {
  def config = [:]
  body.resolveStrategy = Closure.DELEGATE_FIRST
  body.delegate = config
  body()

  pipeline {
    agent {
      label 'linux-agents'
    }
    options { disableConcurrentBuilds() }
    environment {
      AWS_PROFILE             = "${config.hasProperty('aws_profile') ? utility.getAccountIdByProfile(config.aws_profile) : "gdb-delphi-dev"}"
      PROJECT_GROUP           = "delphi"
      ECR                     = "${utility.getAccountIdByProfile(env.AWS_PROFILE)}.dkr.ecr.us-east-1.amazonaws.com"
      OCTOPUS_CLI_SERVER      = "https://octopus.delphi.zone"
      OCTOPUS_CLI_API_KEY     = sh(script: "aws secretsmanager get-secret-value --profile gdb-delphi-dev --secret-id 'infra/jenkins/octopus_api_key' --output json | jq -r .SecretString", , returnStdout: true).trim()
      OCTOPUS_CHANNEL         = octopus.setOctoChannel(env.BRANCH_NAME)
      DEPLOY_ENV              = octopus.setDeploymentEnv(params.DEPLOY_ENV_CHOICE, env.PROJECT_GROUP, env.BRANCH_NAME )
      NOTIFICATIONS_CHANNEL   = "${config.hasProperty('slack_channel') ? config.slack_channel : "delphi-slz-cicd-alerts"}"
    }
    parameters {
      choice(
        choices: [
          'yes',
          'no',
        ],
        description: 'Run unit tests.',
        name: 'RUN_TESTS'
      )
      choice(
        choices: [
          'default',
          'yes',
          'no',
        ],
        description: '''Whether to trigger deployment pipeline(build deployment artifact, create octopus release, deploy it).
        By default it\'s only triggered for develop, release* and master branches.
        ''',
        name: 'TRIGGER_DEPLOY'
      )
      choice(
        choices: [
          'default',
          'dev',
          'qa',
          'stage',
          'skip_deployment'
        ],
        description: 'Set environment for deployment. Skipped by default master/release*, dev by default for all other branches',
        name: 'DEPLOY_ENV_CHOICE'
      )
      choice(
        choices: [
          'error',
          'overwrite',
          'skip_build'
        ],
        description: "Docker image upload mode - ovewrite if the image with such tag already exists, raise error if exists, or skip build part if exists.",
        name: 'IMAGE_UPLOAD_MODE'
      )
      choice(
        choices: [
          'yes',
          'no'
        ],
        description: "Don't raise errors in case release already exists",
        name: 'FAIL_IF_RELEASE_EXISTS'
      )
    }
    stages {
      stage("Generic build stage") {
        steps {
          script {
            parallel(["${config.name}": liquibasePackage_v2.getStage(params, config.name, config.path)])
          }
        }
      }
    }
    post {
      always {
        sh "sudo chown -R ec2-user:ec2-user ${env.WORKSPACE}"
      }
      success {
        script {
          if (currentBuild.getPreviousBuild() &&
              currentBuild.getPreviousBuild().getResult().toString() != "SUCCESS") {
            utility.slackNotifyMainBranches(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
          }
        }
      }
      failure {
        script {
          utility.slackNotifyMainBranches(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
        }
      }
      cleanup {
          deleteDir()
      }
    }
  }
}
