def safebranch='unknown'

pipeline {
  agent any
  options {
      timestamps()
      disableConcurrentBuilds()
      buildDiscarder(logRotator(numToKeepStr: '5'))
      timeout(time: 1, unit: 'HOURS')
  }
  stages {
    stage('Build') {
      steps {
        script {
          safebranch=env.BRANCH_NAME.toLowerCase().replaceAll("[-_/.]", "");
          echo "Building branch ${env.BRANCH_NAME} (escaped as ${safebranch})";
        }
        sh """
          docker build --pull -t docker-repo-rw.techfirm.ch/digital-intake/front:${safebranch} .
        """
      }
      } // stage Build
      stage('Deploy') {
             steps {
              sh """
                  echo "Pushing images with tag ${safebranch}..."
                  docker push docker-repo-rw.techfirm.ch/digital-intake/front:${safebranch}
              """

              sh """
                  echo "Replacing ${safebranch} in descriptors..."
                  sed -i s/RANCHERTAG/${safebranch}/ docker-compose.yml
                  sed -i s/RANCHERTAG/${safebranch}/ rancher-compose.yml
                  sed -i s/RANCHERHOST/digital-intake-${safebranch}.ch.techfirm.cloud/ docker-compose.yml
                  sed -i s/RANCHERHOST/digital-intake-${safebranch}.ch.techfirm.cloud/ rancher-compose.yml
              """
              sh "rancher up --pull --force-upgrade --confirm-upgrade --stack digital-intake-${safebranch} -d"
          } // steps
      }
    } // stages
    post {
      always {
        ansiColor("xterm") {
            sh "docker run --rm -t -v /var/run/docker.sock:/var/run/docker.sock -v \$(pwd):/opt/workspace docker-repo-rw.techfirm.ch/techfirm/housekeeping digital-intake"
        }
      }
    }
} // pipeline
