def branch = "${env.BRANCH_NAME}"
def tag = env.BRANCH_NAME.toUpperCase()
tag = "${tag}-${env.BUILD_NUMBER}"

def service = "{#PROJECT_NAME_KEBAB_LOWERCASE#}" // edit bằng tên module (đây là tên image sau khi được build) không chứa "_"

def imageDeploy = "docker-registry.mobio.vn/${service}"
def tagToDeploy = "${imageDeploy}:${tag}"
def tagToDeployLatest = "${imageDeploy}:latest"

def imageDeployRelease = "registry.mobio.vn/${service}"
def tagToDeployRelease = "${imageDeployRelease}:${tag}"

def agentLabel
if (env.BRANCH_NAME.toUpperCase() == "DEVELOP") {
  agentLabel = "dev"
} else if (env.BRANCH_NAME.toUpperCase() == "MASTER" || env.BRANCH_NAME.toUpperCase() == "HOTFIX") {
  agentLabel = "uat-agent"
}

pipeline {
  agent { label "${agentLabel}"}

  stages {
    stage('Apply\nImage BASE') {
      steps {
        script {
          def filenameDockerfile = "Dockerfile"
          if (env.BRANCH_NAME.toUpperCase() == "MASTER" || env.BRANCH_NAME.toUpperCase() == "HOTFIX") {
            filenameDockerfile = "Dockerfile-release"
          }

          sh ("sed -i 's#BE_BASE_COMPILE_IMAGE#${env.BE_BASE_COMPILE_IMAGE}#g' ${filenameDockerfile}")
          def isReplaceCompileImageSuccess = sh(returnStdout: true, script: "grep -c '${env.BE_BASE_COMPILE_IMAGE}' ${filenameDockerfile}").trim()
          if (isReplaceCompileImageSuccess == 0)
            error ("Chua thay the duoc image BASE(compile)")

          sh ("sed -i 's#BE_BASE_RUN_IMAGE#${env.BE_BASE_RUN_IMAGE}#g' ${filenameDockerfile}")
          def isReplaceRunImageSuccess = sh(returnStdout: true, script: "grep -c '${env.BE_BASE_RUN_IMAGE}' ${filenameDockerfile}").trim()
          if (isReplaceRunImageSuccess == 0)
            error ("Chua thay the duoc image BASE(run)")
        }
      }
    }

    stage('Build image') {
      steps {
        script {
          if (env.BRANCH_NAME.toUpperCase() == "DEVELOP") {
            sh ("docker build -t ${tagToDeploy} -t ${tagToDeployLatest} .")
          } else if (env.BRANCH_NAME.toUpperCase() == "HOTFIX") {
            // get git branch name
            def git_branch_name = GIT_BRANCH.split('/').last().toUpperCase()
            tag = "${git_branch_name}-${env.BUILD_NUMBER}"
            tagToDeployRelease = "${imageDeployRelease}:${tag}"

            sh ("docker build -t ${tagToDeployRelease} -f Dockerfile-release .")

          } else if (env.BRANCH_NAME.toUpperCase() == "MASTER") {
              // build release
              sh ("docker build -t ${tagToDeployRelease} -f Dockerfile-release .")
          }
        }
      }
    }

    stage('Scan security') {
      steps {
        script {
          def tagName = "${tagToDeploy}"
          if (env.BRANCH_NAME.toUpperCase() == "MASTER" || env.BRANCH_NAME.toUpperCase() == "HOTFIX")
            tagName = "${tagToDeployRelease}"

          sh ("trivy -q image --exit-code 1 --format template --template \"@/contrib/html.tpl\" --output trivy_report.html --timeout 30m --ignore-unfixed --security-checks vuln --skip-update ${tagName}")
        }
      }
    }

    stage('Push image') {
      steps {
        script {
          if (env.BRANCH_NAME.toUpperCase() == "DEVELOP") {
            sh ("docker push ${tagToDeploy}")
            sh ("docker push ${tagToDeployLatest}")
          } else if (env.BRANCH_NAME.toUpperCase() == "MASTER") {
            sh ("docker push ${tagToDeployRelease}")

            // commit tag
            sh("git tag ${tag}")
            sh("git push --tags")
          }
        }
      }
    }

    stage ('Run') {
      steps {
        script {
          if (env.BRANCH_NAME.toUpperCase() == "DEVELOP") {
            // apply các file yaml
            sh  ("find ./yaml -type f -name '*.yaml' -exec sed -i 's#{image}#${tagToDeploy}#g; s#{image-monstache}#docker-registry.mobio.vn/mobio_monstache:6-V2#g' {} ';' -printf '%f\t%p\n' | sort -k1 | awk '{system(\"kubectl apply -n mobio -f \" \$2)}'")
            def is_used = true
            def unused_pods = [
            ]
            if (is_used == false) {
              echo "Khong su dung"
              sh ("find ./yaml -name '*.yaml' -type f -exec kubectl scale --replicas=0 -f {} -n mobio ';'")
            }
            else {
              for(file in unused_pods) {
                sh ("find ./yaml -name 'file' -type f -exec kubectl scale --replicas=0 -f {} -n mobio ';'")
                // sh (script: "kubectl scale --replicas=0 -f ./yaml/${file} -n mobio")
              }
            }
          }
        }
      }
    }
  }

  post {
    always {
      archiveArtifacts artifacts: "trivy_report.html", fingerprint: true

      publishHTML (target: [
        allowMissing: true,
        alwaysLinkToLastBuild: true,
        keepAll: true,
        reportDir: '.',
        reportFiles: 'trivy_report.html',
        reportName: 'Trivy Scan',
        ])
  }
}
}