def supportedMobileDevices() {
  return [
    'iPhone 13 Pro,iOS 15',
    'iPhone 12 Pro Max,iOS 16',
    'iPhone 12 Pro Max,iOS 14',
    'iPhone 12 Mini,iOS 14',
    'iPhone 12,iOS 14',
    'iPhone 11,iOS 14',
    'iPhone XS,iOS 12',
    'iPhone 11 Pro,iOS 13',
    'iPhone 11,iOS 13',
    'iPhone 11 Pro Max,iOS 13',
    'iPhone X,iOS 11',
    'iPhone 8,iOS 12',
    'iPhone XS Max,iOS 12',
    'iPhone XR,iOS 14',
    'iPhone 8,iOS 13',
    'iPhone 8,iOS 11',
    'iPhone 8 Plus,iOS 12',
  ]
}

def getReleaseChannelByBranchName(branch) {
  switch (branch) {
    case 'master':
      return 'production'
    case 'develop':
      return 'qa'
    case 'develop2':
      return 'qa2'
    default:
      return 'dev'
  }
}

def getEnvPrefixByReleaseChannel(channel) {
  switch (channel) {
    case 'preprod':
    case ~/production*/:
      return 'prod'
    default:
      return 'dev'
  }
}

def getCmdSuffixFromParams(force, branch) {
  switch (force) {
    case 'ANDROID_BUILD_APK':
      return 'development'
    case 'ANDROID_BUILD_AAB':
    case 'IOS_BUILD':
      return 'production'
    case 'IOS_AD_HOC':
      return 'development'
    case 'IOS_SIMULATOR_BUILD':
      return 'automation'
    default:
      return getCmdSuffixByBranch(branch)
  }
}

def getCmdSuffixByBranch(branch) {
  switch (branch) {
    case 'master':
      return 'production'
    default:
      return 'development'
  }
}

def build(Map config=[:]) {
  def platform = config.platform ?: 'android'
  def runAs = config.runAs ?: 'root'
  def buildCmd = []
  def buildType = config.buildType ?: 'development'
  def url
  def clearCache = config.clearCache ?: false

  if (!config.image) {
    error 'image is required!'
  }

  def releaseChannel = env.RELEASE_CHANNEL

  buildCmd << "eas"
  buildCmd << "build"
  buildCmd << "-p ${platform}"
  buildCmd << "--profile ${releaseChannel}:${buildType}"
  buildCmd << "--non-interactive"
  if (clearCache) {
    buildCmd << "--clear-cache"
  }
  buildCmd << "--json"

  withDockerContainer(image: "${config.image}", args: "--user='${runAs}'") {
    res = sh script: """
        cd /home/node/workspace \
        && ${buildCmd.join(' ')}
      """, returnStdout: true
    echo res
    obj = readJSON text: res
    obj.each {
      url = it.artifacts.buildUrl
      fileName = url.split('/')[-1].trim()
      sh script: """
        mkdir -p artifacts/;
        curl -k -q -L -o artifacts/${fileName} ${url};
      """
    }
  }

  return url
}

def installDependencies() {
  sh label: "Install dependencies", script: """
    # Login to ECR
    set +x
    aws ecr get-login --profile gdb-apollo-dev --no-include-email --region us-east-1 | awk '{print \$6}' | docker login -u AWS --password-stdin "https://${env.ECR}"
    docker pull ${env.ECR}/apollo-go:config-develop
    docker pull ${env.ECR}/apollo-go:develop
    ./build.sh
  """
}

def publishDockerImage() {
  sh label: "publish docker image", script: """
    set +x
    aws ecr get-login --profile gdb-apollo-dev --no-include-email --region us-east-1 | awk '{print \$6}' | docker login -u AWS --password-stdin https://${env.ECR}
    set -x
    docker push ${env.ECR}/apollo-go:config-develop
    docker push ${env.ECR}/apollo-go:develop
  """
}

def runTests() {
  sh """
    docker run \
    -e JEST_JUNIT_OUTPUT_DIR -e JEST_JUNIT_OUTPUT_NAME \
    -v \$(pwd)/output:/home/node/workspace/output \
    apollo-go:${env.IMAGE_TAG} \
    yarn run test:ci
  """
}

def fixPermissions() {
  sh 'sudo chown -R $(whoami):$(whoami) $(pwd)/'
}

def generateAndSyncSwagger() {
  sh """
    docker run \
      --user=root \
      -v \$(pwd)/dist:/home/node/workspace/dist \
      apollo-go:${env.IMAGE_TAG} \
      yarn swagger
  """
  sh label: 'sync swagger documentation', script: 'aws s3 sync dist/ s3://dev-insights-swagger.apollo.stream/'
  sh label: 'invalidate cache', script: 'aws cloudfront create-invalidation --distribution-id E265368OOECECR --paths /*.json'
}

def getBuildStages() {
  def iosLink, androidLinkAAB, androidLinkAPK, androidFileNameAAB, androidFileNameAPK, iosFileName
  return [
    "android_apk": {
      stage('android apk') {
        echo "android apk stage"
        if (params.FORCE.contains('ANDROID_BUILD_APK') || env.BRANCH_NAME.equals('master')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          androidLinkAPK = build(image: "apollo-go:${env.IMAGE_TAG}", buildType: 'development')
          androidFileNameAPK = androidLinkAPK.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download it here:\n${androidLinkAPK}")
          currentBuild.description = currentBuild.description + "\n" + androidLinkAPK
          echo "archive android apk artifact"
          try {
            sh """
              set -e
              aws s3 cp artifacts/${androidFileNameAPK} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${androidFileNameAPK}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      }
    },
    "android_apk_debug": {
      stage('android apk debug') {
        echo "android apk debug stage"
        if (params.FORCE.contains('ANDROID_DEBUG_BUILD_APK')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          androidLinkAPK = build(image: "apollo-go:${env.IMAGE_TAG}", buildType: 'debug')
          androidFileNameAPK = androidLinkAPK.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download it here:\n${androidLinkAPK}")
          currentBuild.description = currentBuild.description + "\n" + androidLinkAPK
          echo "archive android apk artifact"
          try {
            sh """
              set -e
              aws s3 cp artifacts/${androidFileNameAPK} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${androidFileNameAPK}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      }
    },
    "android_aab": {
      stage('android aab') {
        echo "android aab stage"
        if (params.FORCE.contains('ANDROID_BUILD_AAB') || env.BRANCH_NAME.equals('master')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          androidLinkAAB = build(image: "apollo-go:${env.IMAGE_TAG}", buildType: 'production')
          androidFileNameAAB = androidLinkAAB.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download it here:\n${androidLinkAAB}")
          currentBuild.description = currentBuild.description + "\n" + androidLinkAAB
          echo "archive android aab artifact"
          try {
            sh """
              set -e
              aws s3 cp artifacts/${androidFileNameAAB} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${androidFileNameAAB}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      } /** end: stage */
    },
    "ios_ipa": {
      stage('IOS IPA') {
        echo "ios ipa stage"
        if (params.FORCE.contains('IOS_BUILD') || env.BRANCH_NAME.equals('master')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started ios build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          iosLink = build(
                  image: "apollo-go:${env.IMAGE_TAG}",
                  platform: 'ios',
                  simulator: false,
                  adHoc: false,
                  buildType: 'production'
          )
          iosFileName = iosLink.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download here:\n${iosLink}")
          currentBuild.description = currentBuild.description + "\n" + iosLink
          echo "archive ios artifact"
          try {
            sh """
              aws s3 cp artifacts/${iosFileName} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${iosFileName}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      } /** end: stage */
    },
    "ios_simulator": {
      stage('IOS Simulator') {
        echo "ios simulator"
        if (params.FORCE.contains('IOS_SIMULATOR_BUILD')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started ios build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          iosLink = build(
                  image: "apollo-go:${env.IMAGE_TAG}",
                  platform: 'ios',
                  simulator: true,
                  adHoc: false,
                  clearCache: true,
                  buildType: 'automation'
          )
          iosFileName = iosLink.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download here:\n${iosLink}")
          currentBuild.description = currentBuild.description + "\n" + iosLink
          echo "archive ios artifact"
          try {
            sh """
              aws s3 cp artifacts/${iosFileName} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${iosFileName}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      }
    },
    "ios_ad_hoc": {
      stage('IOS AD HOC') {
        echo "ios ad hoc"
        if (params.FORCE.contains('IOS_AD_HOC')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started ios build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          iosLink = build(
                  image: "apollo-go:${env.IMAGE_TAG}",
                  platform: 'ios',
                  simulator: false,
                  adHoc: true,
                  buildType: 'development'
          )
          iosFileName = iosLink.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download here:\n${iosLink}")
          currentBuild.description = currentBuild.description + "\n" + iosLink
          echo "archive ios artifact"
          try {
            sh """
              aws s3 cp artifacts/${iosFileName} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${iosFileName}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      } /** end: stage */
    },
    "ios_ad_hoc_debug": {
      stage('IOS AD HOC DEBUG') {
        echo "ios ad hoc debug"
        if (params.FORCE.contains('IOS_DEBUG_AD_HOC')) {
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "started ios build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} <${env.BUILD_URL}|Open>")
          iosLink = build(
                  image: "apollo-go:${env.IMAGE_TAG}",
                  platform: 'ios',
                  simulator: false,
                  adHoc: true,
                  buildType: 'debug'
          )
          iosFileName = iosLink.split('/')[-1].trim()
          utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL, "finished android build for ${env.JOB_NAME} version ${env.VERSION} to channel ${env.RELEASE_CHANNEL} you can download here:\n${iosLink}")
          currentBuild.description = currentBuild.description + "\n" + iosLink
          echo "archive ios artifact"
          try {
            sh """
              aws s3 cp artifacts/${iosFileName} s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/
            """
            currentBuild.description = currentBuild.description + "\n" + "s3://${env.ARTIFACTS_S3_BUCKET}/${env.RELEASE_CHANNEL}/${env.VERSION}/${env.DATE2PATH}/${iosFileName}"
          } finally {
            sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          }
        }
      } /** end: stage */
    }
  ]
}
