#!groovy
@Library('infraLib') _

def buildInfo
def buildDescription
def buildDisplayName
def devicesList = apolloGoHelpers.supportedMobileDevices()

def releaseChannelToTargetURL(releaseChannel) {
    switch(releaseChannel) {
        case 'qa':
        case 'qa2':
        case 'dev':
        case 'dev2':
            return 'https://dev-proxy.apollo.stream'
        case 'staging':
            return 'https://stage-proxy.apollo.stream'
        case 'test':
            return 'https://test-proxy.apollo.stream'
        case 'production':
            return 'https://proxy.apollo.stream'
    }
}

pipeline {
    agent none

    options {
        buildDiscarder logRotator(artifactDaysToKeepStr: '',
                                  artifactNumToKeepStr: '',
                                  daysToKeepStr: '',
                                  numToKeepStr: '30')
        disableResume()
        ansiColor('xterm')
    }

    parameters {
        separator(name: 'ago-wrapper-build-params', sectionHeader: 'Build parameters')
        listGitBranches(
          branchFilter: '.*',
          credentialsId: 'theorchard-ci-ssh-key',
          defaultValue: 'refs/heads/develop',
          name: 'APOLLO_GO_BRANCH',
          quickFilterEnabled: true,
          remoteURL: 'git@github.com:theorchard/apollo-go.git',
          selectedValue: 'DEFAULT',
          sortMode: 'NONE',
          tagFilter: '*',
          type: 'PT_BRANCH_TAG'
        )
        choice(
          choices: [
            'Please make a choice',
            'qa',
            'qa2',
            'dev',
            'dev2',
            'staging',
            'test',
            'uat',
            'production',
          ],
          name: 'RELEASE_CHANNEL',
          description: 'Expo channel'
        )
        choice(
          choices: [
            'ANDROID_BUILD_APK',
            'ANDROID_BUILD_AAB',
            'ANDROID_DEBUG_BUILD_APK',
            'IOS_BUILD',
            'IOS_SIMULATOR_BUILD',
            'IOS_AD_HOC',
            'IOS_DEBUG_AD_HOC',
          ],
          name: 'FORCE',
          description: 'Force a build.'
        )
        separator(name: 'ago-wrapper-test-params', sectionHeader: 'Test parameters')
        listGitBranches(
          branchFilter: '.*',
          credentialsId: 'theorchard-ci-ssh-key',
          defaultValue: 'refs/heads/master',
          name: 'APOLLO_GO_MOBILE_AUTO_BRANCH',
          quickFilterEnabled: true,
          remoteURL: 'git@github.com:theorchard/apollo-go-mobile-automation.git',
          selectedValue: 'DEFAULT',
          sortMode: 'NONE',
          tagFilter: '*',
          type: 'PT_BRANCH_TAG'
        )
        choice(
          choices: [
            'Please make a choice',
            'UI SMOKE',
            'UI FULL'
          ],
          name: 'FORCE_BUILD',
          description: 'Run full or smoke UI tests'
        )
        choice(
          choices: devicesList,
          description: 'Choose a device',
          name: 'IOS_DEVICE_VERSION'
        )
        choice(
          choices: [
            '5',
            '4',
            '3',
            '2',
            '1',
            '6', // we have been given additional 5 executors
            '7',
            '8',
            '9',
            '10'
          ],
          description: 'Choose a device',
          name: 'NUMBER_OF_PARALLEL_TESTS'
        )
        string (
          defaultValue: '',
          description: 'Limit check to these UI tests only',
          name: 'UI_TESTS',
          trim: true
        )
        string (
          defaultValue: '',
          description: 'Copy allure report from this build',
          name: 'PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER',
          trim: true
        )
    }

    stages {
      stage('Validate Input') {
        when {
          allOf {
            not { expression { return params.FORCE_BUILD.equals('Please make a choice') } } // FORCE_BUILD != 'Please make a choice'
            not { expression { return params.FORCE.equals('AD_HOC') } } // FORCE != 'AD_HOC'
          }
        } /** end: when */
        steps {
          echo "this step is temporary disabled"
          // error 'Wrong set of input parameters'
        } /** end: steps */
      } /** end: stage */

      stage('Build') {
        environment {
          BRANCH_OR_TAG = "${params.APOLLO_GO_BRANCH.minus('refs/heads/')}".replace('/', '%2F')
        }
        steps {
          script {
            currentBuild.description = """branch: ${env.BRANCH_OR_TAG}
channel: ${params.RELEASE_CHANNEL}
isAndroidBuild = ${params.FORCE == 'ANDROID_BUILD'}
isiOSBuild = ${params.FORCE == 'IOS_BUILD'}
isiOSSimulatorBuild = ${params.FORCE == 'IOS_SIMULATOR_BUILD'}
isAdHocCert = ${params.FORCE == 'IOS_AD_HOC'}
"""
            buildInfo = build job: "ApolloGo/pipelines/apollo-go/${env.BRANCH_OR_TAG}",
                              parameters: [
                                string(name: 'RELEASE_CHANNEL', value: params.RELEASE_CHANNEL),
                                string(name: 'FORCE', value: params.FORCE),
                                booleanParam(name: 'SKIP_STYLE_LINT', value: true),
                                booleanParam(name: 'SKIP_LINTER', value: true),
                                booleanParam(name: 'SKIP_TESTS', value: true),
                                booleanParam(name: 'SKIP_TS_LINT', value: true),
                              ]
            buildDescription = buildInfo.getDescription().trim().split("\n").first()
            buildDisplayName = buildInfo.getDisplayName().trim().split('-').first()
          } /** end: script */
        } /** end: steps */
      } /** end: stage */

      stage('UI Test') {
        when {
          allOf {
            not { expression { return params.FORCE_BUILD.equals('Please make a choice') } }
            expression { return FORCE.equals('IOS_AD_HOC') }
            /** TODO: define which channels we support */
          }
        }
        environment {
          FILE_URL      = "${buildDescription}"
          IOS_BUILD     = "${buildDisplayName}"
          BRANCH_OR_TAG = "${params.APOLLO_GO_MOBILE_AUTO_BRANCH.minus('refs/heads/')}".replace('/', '%2F')
        }
        steps {
          build job: "ApolloGo/pipelines/apollo-go-mobile-automation/${env.BRANCH_OR_TAG}",
                parameters: [
                  string(name: 'FORCE_BUILD', value: params.FORCE_BUILD),
                  string(name: 'FILE_URL', value: env.FILE_URL),
                  string(name: 'IOS_BUILD', value: env.IOS_BUILD),
                  string(name: 'IOS_DEVICE_VERSION', value: env.IOS_DEVICE_VERSION),
                  string(name: 'NUMBER_OF_PARALLEL_TESTS', value: params.NUMBER_OF_PARALLEL_TESTS),
                  string(name: 'TARGET_API_URL', value: releaseChannelToTargetURL(params.RELEASE_CHANNEL)),
                  string(name: 'UI_TESTS', value: params.UI_TESTS),
                  string(name: 'PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER', value: params.PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER),
                  booleanParam(name: 'USE_CACHE', value: env.BRANCH_OR_TAG == 'master')
                ]
        } /** end: steps */
      } /** end: stage */
  } /** end: stages */
} /** end: pipeline */
