#!/bin/groovy
/*
 * Licensed to Open Source Radio Access Network(OS-RAN) Alliance and OAI
 * Software Alliance under one or more contributor license agreements. The
 * initial OpenXG series projects are derided from OAI projects, the files from
 * OAI projects are all in compliance with OAI Public License, Version 1.1.
 * codes and files developed from OpenXG projects and from OS-RAN Alliance
 * are all under OS-RAN licenses; you may not use this file except in compliance
 * with the license.  You may get a copy of the license at:
 * 	http://www.openxg.org.cn/?falu_69.html
 * For more information about OpenXG, please contact:
 * 	contact@openxg.org.cn
 */

// Location of the python executor node shall be in the same subnet as the others servers
def nodeExecutor = params.nodeExecutor

// Name of the phone resource
def ciServerResource = params.serverResource

pipeline {
  agent {
    label nodeExecutor
  }
  options {
    disableConcurrentBuilds()
    ansiColor('xterm')
    lock (ciServerResource)
  }
  stages {
    stage ("Verify Parameters") {
      steps {
        script {
          echo '\u2705 \u001B[32mVerify Parameters\u001B[0m'
          def allParametersPresent = true

          // It is already to late to check it
          if (params.nodeExecutor != null) {
            echo "Docker Push executor node  :   ${nodeExecutor}"
          }
          if (params.serverResource == null) {
            allParametersPresent = false
          }
        }
      }
    }
    stage ("Push to DockerHub") {
      steps {
        script {
          WEEK_TAG = sh returnStdout: true, script: 'date +"%Y.w%U"'
          WEEK_TAG = WEEK_TAG.trim()

          withCredentials([
            [$class: 'UsernamePasswordMultiBinding', credentialsId: "${params.DH_Credentials}", usernameVariable: 'DH_Username', passwordVariable: 'DH_Password']
          ]) {
            def listOfImages = ["oai-enb", "oai-gnb", "oai-lte-ue", "oai-nr-ue"]
            sh "docker login -u ${DH_Username} -p ${DH_Password} > /dev/null 2>&1"
            listOfImages.eachWithIndex { item, iindex ->
              sh "docker image tag ${item}:develop ${DH_Username}/${item}:develop"
              sh "docker image tag ${item}:develop ${DH_Username}/${item}:${WEEK_TAG}"
              sh "docker push --quiet ${DH_Username}/${item}:${WEEK_TAG}"
              sh "docker push --quiet ${DH_Username}/${item}:develop"
              sh "docker rmi ${DH_Username}/${item}:${WEEK_TAG} ${DH_Username}/${item}:develop"
            }
            sh "docker logout > /dev/null 2>&1"
          }
        }
      }
    }
  }
  post {
    always {
      script {
        echo "End of Registry Push"
      }
    }
  }
}