
// uses declarative syntax to run commands inside a container.
pipeline {
  environment {
    BITBUCKET_WORKSPACE = "${JOB_NAME.split(/\//)[0]}"
    APP_NAME = "${JOB_NAME.split(/\//)[1]}"
    APP_PROXY_NAME = "${JOB_NAME.split(/\//)[1]}-proxy"
    PROJECT = "${APP_NAME.split(/-/)[0]}"
    
    // ecr config
    // AWS_ACCESS_KEY_ID = credentials('stellantis-aws-access-key-id')
    // AWS_SECRET_ACCESS_KEY = credentials('stellantis-aws-secret-access-key')
    // AWS_DEFAULT_REGION = "me-south-1"
    // CLIENT_REGISTRY_AWS = "895506467979.dkr.ecr.me-south-1.amazonaws.com"
    REGISTRY = "registry.cloud.ispgnet.com"
    REGISTRY_CRED = credentials('credentials-registry-ispg-cloud')
    // gitops config
    GITOPS_REPO = "https://bitbucket.org/${BITBUCKET_WORKSPACE}/${PROJECT}-gitops.git"
    GITOPS_DIR = "${APP_NAME}"
  }

  agent {
      kubernetes {
          yamlFile 'jenkins-agent-pod.yaml'
      }
  }

  stages {


    stage('sonar_scan_2') {
      when { anyOf { branch 'develop'; branch 'preprod'; branch 'master'; branch 'staging' } }
      environment {
        SONAR_TOKEN=credentials('sonarscan-token')
        SONAR_HOST_URL="https://sonarqube-scans.cloud.ispgnet.com"
        PROJECT_REPO = "${JOB_NAME.split(/\//)[1]}-${BRANCH_NAME}"
      }
      steps {
        container('sonar') {
          sh '''
            sonar-scanner -Dsonar.projectKey=${PROJECT_REPO} \
              -Dsonar.sources=. \
              -Dsonar.token=$SONAR_TOKEN \
              -Dsonar.host.url=$SONAR_HOST_URL
          '''
        }
      }
    }


    stage('Build & Publish') {
      when { anyOf { branch 'develop'; branch 'staging'; branch 'preprod'; branch 'master' } }
      steps {
        container('docker') {
          sh '''                     
            echo "logging to registry..." 
            if [[ $BRANCH_NAME == "master" ]]; then
              aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | docker login --username AWS --password-stdin ${CLIENT_REGISTRY_AWS}
              APP_REPO="${CLIENT_REGISTRY_AWS}/${APP_NAME}-${BRANCH_NAME}"
              APP_PROXY_REPO="${CLIENT_REGISTRY_AWS}/${APP_NAME}-proxy-${BRANCH_NAME}"
            else           
              docker login -u ${REGISTRY_CRED_USR} -p ${REGISTRY_CRED_PSW} ${REGISTRY}
              APP_REPO="${REGISTRY}/${PROJECT}/${APP_NAME}-${BRANCH_NAME}"
              APP_PROXY_REPO="${REGISTRY}/${PROJECT}/${APP_NAME}-proxy-${BRANCH_NAME}"
            fi
            echo "building app. image..."
            docker build -t ${APP_REPO}:${BUILD_NUMBER} .  
            
            echo "building app. proxy image..."
            docker build -f Dockerfile.nginx -t ${APP_PROXY_REPO}:${BUILD_NUMBER} .

            echo "publishing app. image..."
            docker push ${APP_REPO}:${BUILD_NUMBER}

            echo "publishing app. proxy image..."            
            docker push ${APP_PROXY_REPO}:${BUILD_NUMBER} 
          '''          
        }
      }
    }

    stage('GitOps') {
      when { anyOf { branch 'develop'; branch 'staging'; branch 'preprod'; branch 'master' } }
      environment {
        GIT_AUTH = credentials('bitbucket-ispgweb-devopsbot') 
      }
      steps {
        checkout([
          $class: 'GitSCM', 
          branches: [[name: 'refs/heads/master']],
          userRemoteConfigs: [[
            url: env.GITOPS_REPO,
            name: 'origin',
            refspec: '+refs/heads/master:refs/remotes/origin/master',
            credentialsId:'bitbucket-ispgweb-devopsbot', 
           ]],
        ])   
        container('yq') {   
          sh 'yq e ".image.tag = ${BUILD_NUMBER}" -i ${GITOPS_DIR}/values-${BRANCH_NAME}.yaml'       
          sh 'yq e ".proxy.image.tag = ${BUILD_NUMBER}" -i ${GITOPS_DIR}/values-${BRANCH_NAME}.yaml'       
        }
        container('git') {
          // https://support.cloudbees.com/hc/en-us/articles/360027646491-Pipeline-Equivalent-to-Git-Publisher      
          sh '''
            git config user.email 'devopsbot@ispgweb.com'
            git config user.name 'devopsbot-ispgweb'
            git commit -am "${BRANCH_NAME} ${GITOPS_DIR} image updated to ${BUILD_NUMBER}"
            git config --local credential.helper "!f() { echo username=\\$GIT_AUTH_USR; echo password=\\$GIT_AUTH_PSW; }; f"
          '''
        }
        container('git') {
          retry(10) {
            sh 'git pull --rebase --no-edit origin HEAD'
            sh 'git push origin HEAD:master'
          }
        }        
      } 
    }      
 
  } // end of all stages
  
  post {
    failure {
      step([$class: 'Mailer', notifyEveryUnstableBuild: true,
        recipients: emailextrecipients([
          [$class: 'DevelopersRecipientProvider'],
          [$class: 'RequesterRecipientProvider']
        ])])
    }
  }

} //  end of pipeline