def SERIAL
def ENAMES = [ 'prod', 'dev' ]

//def ENAMES = [ 'dev' ]


def CLUSTERS = ['prod': 'iru-swarm.infoclinica.lan', 'dev': 'dev-iru-swarm.infoclinica.lan']
def REGISTRIES = ['prod': 'registry.infoclinica.ru:5000', 'dev': 'dev-registry.infoclinica.ru:5000']

pipeline {
  agent {
    label "swarm"
  }
  environment {
    NGINX_GOST_GIT_URL='https://git.sdsys.ru/iru/nginx-gost.git'
    DOCKER_IMAGE='letsencrypt'
    SERVICE_NAME='proxy_letsencrypt'
    DOCKER_CERT_PATH='/run/secrets/swarm'
    JENKINS_MAIL='jenkins.dev@sdsys.ru'
    SWARM_GIT_NAME='stack-deploy'
    SWARM_GIT_URL='ssh://git@git.sdsys.ru:8022/iru/stack-deploy.git'
  }
  parameters {
    string(
      name: "branch",
      defaultValue: "master",
      description: "Which branch to use."
    )
    string(
      name: "mailto",
      defaultValue: "admin@sdsys.ru",
      description: "Email which has to be notified."
    )
  }
  stages {
    stage ("Discover SERIAL") {
      steps {
        script {
          SERIAL = sh script: "echo -n `date +%y%m%d``printf %03d $BUILD_NUMBER`", returnStdout: true
        }
      }
    }
    stage ("Build Image") {
      steps {
        echo "\u001B[32m \u2600 Building \u001B[35m ${DOCKER_IMAGE}:${SERIAL}. \u001B[0m"
        sh "docker build --no-cache -t ${DOCKER_IMAGE}:${SERIAL} ."
      }
    }
    stage ("Push to registry") {
      steps {
        script {
          ENAMES.each { item ->
             echo "Pushing to: ${item}, REGISTRIES ${REGISTRIES.get((item))}"
             sh """docker tag ${DOCKER_IMAGE}:${SERIAL} ${REGISTRIES.get((item))}/${DOCKER_IMAGE}:${SERIAL}
                   docker push ${REGISTRIES.get((item))}/${DOCKER_IMAGE}:${SERIAL}
                """
          }
        }
      }
    }
    stage ("Deploy") {
      steps {
        script {
          ENAMES.each { item ->
             echo "Deploy to: ${item}, CLUSTERS ${CLUSTERS.get((item))}"
             try{
                sh "DOCKER_HOST=tcp://${CLUSTERS.get((item))}:2376 DOCKER_TLS_VERIFY=1 docker service update ${SERVICE_NAME} --image ${REGISTRIES.get((item))}/${DOCKER_IMAGE}:${SERIAL}"
             }
             catch(err){
                echo "Recovering service $item"
                sh "DOCKER_HOST=tcp://${CLUSTERS.get((item))}:2376 DOCKER_TLS_VERIFY=1 docker service rollback ${SERVICE_NAME}"
                throw err
             }
          }
        }
      }
    }
    stage("Tagging") {
        steps {
          echo "Updating tag info in ${SWARM_GIT_NAME} repository"
          withCredentials([sshUserPrivateKey(credentialsId: 'provision', keyFileVariable: 'GIT_SSH_KEY', passphraseVariable: '', usernameVariable: 'GIT_SSH_USERNAME')]) {
            sh """GIT_SSH_COMMAND='ssh -i $GIT_SSH_KEY -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' \
                  git clone \${SWARM_GIT_URL} && cd \${SWARM_GIT_NAME}
                  if [ \$(git branch --list -a | grep -q ${branch}; echo \$?) == 0 ];then echo "${branch} is already exist";git checkout ${branch}; \
                  else echo "${branch} does not exist!!!"; git checkout -b \${branch};fi
                  echo -n ${SERIAL} > tags/${DOCKER_IMAGE}.version
                  git add -A
                  git config --global user.email "${JENKINS_MAIL}"
                  git config --global user.name "Jenkins"
                  git commit -m 'Version update'
                  GIT_SSH_COMMAND='ssh -i ${GIT_SSH_KEY} -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' \
                  git push origin ${branch}
               """
        }
      }
    }
  }
  post {
    always {
      echo "CleaningUp work directory"
      deleteDir()
      sh "docker image rm -f `docker image ls -q ${DOCKER_IMAGE}:${SERIAL}`"

    }
    failure {
      mail charset: 'UTF-8',
           subject: "Jenkins build ERROR",
           mimeType: 'text/html',
           to: "${mailto}",
           body: "<b>ATTENTION!!!</b> <b><br> Jenkins job failed.\n\n <b><br>Project Name:</b> ${env.JOB_NAME} <b><br>\nBuild Number:</b> ${env.BUILD_NUMBER} <b><br>\nURL Build:</b> ${RUN_DISPLAY_URL}"
    }
    success {
      mail charset: 'UTF-8',
           subject: "Jenkins build SUSCCESS",
           mimeType: 'text/html',
           to: "${mailto}",
           body: "<b>Congradulations!!!</b> <b><br> Jenkins job succefully finished.\n\n <b><br>Project Name:</b> ${env.JOB_NAME} <b><br>\nBuild Number:</b> ${env.BUILD_NUMBER} <b><br>\nURL Build:</b> ${RUN_DISPLAY_URL}"
    }
  }
}