// We need release builds for users who want to test apps, diawi removes old builds and limits downloads, hence the need for Artifactory.
// To see env: echo sh(returnStdout: true, script: 'env')

env.LANG="en_US.UTF-8"
env.LANGUAGE="en_US.UTF-8"
env.LC_ALL="en_US.UTF-8"

def installJSDeps() {
    def attempt = 1
    def maxAttempts = 10
    def installed = false
    while (!installed && attempt <= maxAttempts) {
        println "#${attempt} attempt to install npm deps"
        sh 'npm install'
        installed = fileExists('node_modules/web3/index.js')
        attemp = attempt + 1
    }
}

node ('macos1'){
  def apkUrl = ''
  def ipaUrl = ''
  def testPassed = true
  def version

  load "$HOME/env.groovy"

  try {

    stage('Git & Dependencies') {
      slackSend color: 'good', message: BRANCH_NAME + ' build started. ' + env.BUILD_URL

      if (!BRANCH_NAME.startsWith("release/")){
        error "Wrong branch name format: " + BRANCH_NAME + ", but it should be `release/version`"
      }

      checkout scm

      version = BRANCH_NAME.substring(8)
      sh 'echo "' + version + '" > .version'

      sh 'git fetch --tags'

      sh 'rm -rf node_modules'
      sh 'cp .env.prod .env'
      sh 'lein deps'
      installJSDeps()

      sh 'mvn -f modules/react-native-status/ios/RCTStatus dependency:unpack'
        sh 'cd ios && pod install && cd ..'
      }

    stage('Tests') {
      sh 'lein test-cljs'
    }

    stage('Build') {
      sh 'lein prod-build'
    }

    stage('Build (Android)') {
      sh 'cd android && ./gradlew assembleRelease -PreleaseVersion=' + version
    }

    stage('Build (iOS)') {
      def build_no = sh(returnStdout: true, script: './build_no.sh --tag').trim()
      sh ('plutil -replace CFBundleShortVersionString  -string ' + version + ' ios/StatusIm/Info.plist')
      sh ('plutil -replace CFBundleVersion  -string ' + build_no + ' ios/StatusIm/Info.plist')
      sh 'export RCT_NO_LAUNCH_PACKAGER=true && xcodebuild -workspace ios/StatusIm.xcworkspace -scheme StatusIm -configuration release -archivePath status clean archive'
      sh 'xcodebuild -exportArchive -exportPath status -archivePath status.xcarchive -exportOptionsPlist ~/archive.plist'
    }

    stage('Deploy (Android)') {
      def artifact_dir = pwd() + '/android/app/build/outputs/apk/release/'
      println (artifact_dir + 'app-release.apk')
      sh ('ls -la ' + artifact_dir)
      def artifact = (artifact_dir + 'app-release.apk')
      def server = Artifactory.server('artifacts')
      def shortCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim().take(6)
      def filename = 'im.status.ethereum-' + shortCommit + '.apk'
      def newArtifact = (artifact_dir + filename)
      sh ('mv ' + artifact + ' '  + newArtifact)
      def uploadSpec = '{ "files": [ { "pattern": "*apk/release/' + filename + '", "target": "nightlies-local" }]}'
      def buildInfo = server.upload(uploadSpec)
      apkUrl = 'http://artifacts.status.im:8081/artifactory/nightlies-local/' + filename

      sh ('echo ARTIFACT Android: ' + apkUrl)
    }

    stage('Deploy (iOS)') {
      withCredentials([string(credentialsId: 'diawi-token', variable: 'token')]) {
        def job = sh(returnStdout: true, script: 'curl https://upload.diawi.com/ -F token='+token+' -F file=@status/StatusIm.ipa -F find_by_udid=0 -F wall_of_apps=0 | jq -r ".job"').trim()
        sh 'sleep 10'
        def hash = sh(returnStdout: true, script: "curl -vvv 'https://upload.diawi.com/status?token="+token+"&job="+job+"'|jq -r '.hash'").trim()
        ipaUrl = 'https://i.diawi.com/' + hash

        sh ('echo ARTIFACT iOS: ' + ipaUrl)
      }
    }

    stage('Push build tag') {
      withCredentials([[
        $class: 'UsernamePasswordMultiBinding',
        credentialsId: 'jenkins-status-im',
        usernameVariable: 'GIT_USER',
        passwordVariable: 'GIT_PASS'
      ]]) {
        sh ('git push --tags https://${GIT_USER}:${GIT_PASS}@github.com/status-im/status-react --tags')
      }
    }
  } catch (e) {
    slackSend color: 'bad', message: 'Release build failed to build. ' + env.BUILD_URL
    throw e
  }

  stage('Slack Notification') {
    def c = (testPassed ? 'good' : 'warning' )
    slackSend color: c, message: 'Release build \nTests: ' + (testPassed ? ':+1:' : ':-1:') + ')\nAndroid: ' + apkUrl + '\n iOS: ' + ipaUrl
  }
}