package com.freeleaps.devops

class ArgoApplicationVersionUpdater {
  def steps
  def workspace
  def configurations

  ArgoApplicationVersionUpdater(steps, configurations) {
    this.steps = steps
    this.configurations = configurations
    this.workspace = steps.env.WORKSPACE
  }

  def update(environmentSlug, component) {
    steps.log.info("ArgoApplicationVersionUpdater", "[${environmentSlug}] Update Argo application image version to ${steps.env.BUILD_IMAGE_VERSION} for ${component.name}...")

    def userSpecifiedArgoControlledRepo = false
    def argoControlledRepo = component.argoControlledRepo
    if (argoControlledRepo != null && !argoControlledRepo.isEmpty()) {
      userSpecifiedArgoControlledRepo = true
    }

    def repoUrl = "https://gitea.freeleaps.mathmast.com/freeleaps/freeleaps-ops.git"
    def repoCredentialsId = "freeleaps-ops-credentials"
    def repoBranch = "master"
    def valuesFile = "./${configurations.serviceName}/helm-pkg/${component.name}/values.${environmentSlug}.yaml"

    if (userSpecifiedArgoControlledRepo) {
      repoUrl = component.argoControlledRepo
      repoCredentialsId = component.argoControlledRepoCredentialsId
      repoBranch = component.argoControlledRepoBranch
      valuesFile = ".freeleaps/devops/helm-pkg/values.${environmentSlug}.yaml"
      steps.log.info("ArgoApplicationVersionUpdater", "[${environmentSlug}] User specified argo controlled repo: ${argoControlledRepo}")
    } else {
      steps.log.info("ArgoApplicationVersionUpdater", "[${environmentSlug}] Using default argo controlled repo: freeleaps-ops")
    }

    steps.log.info("ArgoApplicationVersionUpdater", "[${environmentSlug}] Pull argo controlled repo from ${repoUrl} to workspace...")

    steps.dir("${workspace}") {
      steps.git branch: repoBranch, credentialsId: repoCredentialsId, url: repoUrl
    }

    steps.dir("${workspace}") {
      steps.log.info("ArgoApplicationVersionUpdater", "[${environmentSlug}] Update ${valuesFile}...")
      def data = steps.readYaml(file: valuesFile)
      data[component.name].image.registry = steps.env.BUILD_IMAGE_REGISTRY
      data[component.name].image.repository = steps.env.BUILD_IMAGE_REPOSITORY
      data[component.name].image.tag = steps.env.BUILD_IMAGE_VERSION
      data[component.name].image.name = steps.env.BUILD_IMAGE_NAME
      steps.writeYaml(file: valuesFile, data: data, overwrite: true)

      steps.withCredentials([steps.usernamePassword(credentialsId: repoCredentialsId, passwordVariable: 'OPS_GIT_PASSWORD', usernameVariable: 'OPS_GIT_USERNAME')]) {
        def ciOriginUrl = "https://${steps.env.OPS_GIT_USERNAME}:${steps.env.OPS_GIT_PASSWORD}@gitea.freeleaps.mathmast.com/freeleaps/freeleaps-ops.git"
        if (userSpecifiedArgoControlledRepo) {
          // argoControlledRepo is a git url, so we need add username and password to the url
          def argoControlledRepoUrlObj = new URL(component.argoControlledRepo)
          if (argoControlledRepoUrlObj.port != null) {
            ciOriginUrl = "${argoControlledRepoUrlObj.protocol}://${steps.env.OPS_GIT_USERNAME}:${steps.env.OPS_GIT_PASSWORD}@${argoControlledRepoUrlObj.host}:${argoControlledRepoUrlObj.port}${argoControlledRepoUrlObj.path}"
          } else {
            ciOriginUrl = "${argoControlledRepoUrlObj.protocol}://${steps.env.OPS_GIT_USERNAME}:${steps.env.OPS_GIT_PASSWORD}@${argoControlledRepoUrlObj.host}${argoControlledRepoUrlObj.path}"
          }
        }
        steps.sh """
          #!/bin/bash

          echo "Set ${workspace} as a safe directory..."
          git config --global --add safe.directory ${workspace}

          echo "Configure git user..."
          git config user.name "freeleaps-gitops-bot"
          git config user.email "gitops@mathmast.com"

          echo "Add and commit changes..."
          git remote add ci_origin ${ciOriginUrl}

          git add ${valuesFile}

          if ! git diff --cached --quiet; then
            git commit -m "ci(bump): bump ${component.name} image version for ${environmentSlug} to ${steps.env.BUILD_IMAGE_VERSION}"
            echo "Detected changes, commit created."
          else
            echo "No changes detected, skipping commit."
          fi

          echo "Push changes to freeleaps-ops repository..."
          git push ci_origin HEAD:${repoBranch}

          echo "Done."
        """
        steps.log.info("ArgoApplicationVersionUpdater", "[${environmentSlug}] ${component.name} image version bump to ${steps.env.BUILD_IMAGE_VERSION}")
      }
    }
  }
}