variables:
  GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"

  CONFIG_SERVER_SERVICE_DIR: "services/spring-cloud-config-server"
  CONFIG_SERVER_HELM_CHART_DIR: "helm/spring-cloud-config-server"
  CONFIG_SERVER_HELM_RELEASE: "spring-cloud-config-server"
  CONFIG_SERVER_IMAGE_REPOSITORY: "$INTERNAL_REGISTRY/pcp-cloud-config-server"
  CONFIG_SERVER_IMAGE_TAG: "$CI_COMMIT_SHORT_SHA"
  CONFIG_SERVER_K8S_NAMESPACE_DEV: "pcp-dev"
  CONFIG_SERVER_GIT_SECRET_NAME: "spring-cloud-config-server-git"
  CONFIG_GIT_URI: "https://git.nstart.cloud/emelianov.an/pcp.git"
  CONFIG_GIT_USERNAME: "gitlab+deploy-token-1"
  CONFIG_GIT_DEFAULT_LABEL: "master"
  CONFIG_GIT_SEARCH_PATHS: "config-repo"
  CONFIG_GIT_SKIP_SSL_VALIDATION: "true"

.config_server_changes: &config_server_changes
  - services/spring-cloud-config-server/**/*
  - build.gradle.kts
  - settings.gradle.kts
  - .gitlab/ci/spring-cloud-config-server.yml
  - helm/spring-cloud-config-server/**/*
  - deploy/**/*

.config-server:rules:build-and-image:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      changes: *config_server_changes
    - if: '$CI_COMMIT_BRANCH == "dev"'
      changes: *config_server_changes
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes: *config_server_changes
    - when: never

.config-server:rules:test:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      changes: *config_server_changes
    - if: '$CI_COMMIT_BRANCH == "dev"'
      changes: *config_server_changes
      when: manual
    - if: '$CI_COMMIT_BRANCH == "master"'
      changes: *config_server_changes
    - when: never

.config-server:rules:deploy-dev:
  rules:
    - if: '$CI_COMMIT_BRANCH == "dev"'
      changes: *config_server_changes
      when: manual
    - when: never

.config-server:gradle-cache:
  cache:
    key: "gradle-config-server-$CI_DEFAULT_BRANCH"
    paths:
      - .gradle/wrapper
      - .gradle/caches
    policy: pull-push

.config-server:docker-build:
  image: repo.nstart.cloud/library/docker:26
  services:
    - name: repo.nstart.cloud/library/docker:26-dind
      alias: docker
      command: ["--tls=false", "--insecure-registry=registry.k8s.265.nstart.local"]
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""
    DOCKER_BUILDKIT: "1"
  before_script:
    - docker version
    - docker info

.config-server:helm-deploy:
  image: repo.nstart.cloud/dtzar/helm-kubectl:3.14.0
  before_script:
    - mkdir -p /root/.kube
    - helm version
  after_script:
    - rm -f /root/.kube/config

config-server:test:
  stage: test
  image: repo.nstart.cloud/library/gradle:jdk17-ubi10
  extends:
    - .config-server:rules:test
    - .config-server:gradle-cache
  before_script:
    - chmod +x gradlew
  script:
    - ./gradlew --no-daemon :services:spring-cloud-config-server:test
  artifacts:
    when: always
    reports:
      junit:
        - services/spring-cloud-config-server/build/test-results/test/*.xml
    paths:
      - services/spring-cloud-config-server/build/reports/tests/
    expire_in: 7 days

config-server:build:
  stage: build
  image: repo.nstart.cloud/library/gradle:jdk17-ubi10
  extends:
    - .config-server:rules:build-and-image
    - .config-server:gradle-cache
  needs:
    - job: config-server:test
      artifacts: true
  before_script:
    - chmod +x gradlew
  script:
    - ./gradlew --no-daemon :services:spring-cloud-config-server:bootJar
  artifacts:
    when: always
    paths:
      - services/spring-cloud-config-server/build/libs/*.jar
    expire_in: 7 days

config-server:package:
  stage: package
  extends:
    - .config-server:rules:build-and-image
    - .config-server:docker-build
  needs:
    - job: config-server:build
      artifacts: true
  script:
    - 'echo "CONFIG_SERVER_IMAGE_REPOSITORY=$CONFIG_SERVER_IMAGE_REPOSITORY"'
    - |
      JAR_COUNT="$(find "$CONFIG_SERVER_SERVICE_DIR/build/libs" -maxdepth 1 -type f -name '*.jar' ! -name '*-plain.jar' | wc -l)"

      if [ "$JAR_COUNT" -ne 1 ]; then
        echo "Expected exactly one executable jar, found: $JAR_COUNT"
        find "$CONFIG_SERVER_SERVICE_DIR/build/libs" -maxdepth 1 -type f -name '*.jar' -print || true
        exit 1
      fi

      JAR_FILE="$(find "$CONFIG_SERVER_SERVICE_DIR/build/libs" -maxdepth 1 -type f -name '*.jar' ! -name '*-plain.jar' | head -n 1)"
    - rm -rf docker-context
    - mkdir -p docker-context/build/libs
    - cp "$CONFIG_SERVER_SERVICE_DIR/Dockerfile" docker-context/Dockerfile
    - cp "$JAR_FILE" docker-context/build/libs/app.jar
    - find docker-context -maxdepth 4 -type f -print -exec ls -la {} \;
    - docker build --file docker-context/Dockerfile --tag "$CONFIG_SERVER_IMAGE_REPOSITORY:$CONFIG_SERVER_IMAGE_TAG" docker-context
    - docker push "$CONFIG_SERVER_IMAGE_REPOSITORY:$CONFIG_SERVER_IMAGE_TAG"
    - printf "CONFIG_SERVER_IMAGE=%s\n" "$CONFIG_SERVER_IMAGE_REPOSITORY:$CONFIG_SERVER_IMAGE_TAG" > config-server-image.env
  artifacts:
    reports:
      dotenv: config-server-image.env
    expire_in: 7 days

config-server:deploy:dev:
  stage: deploy
  extends:
    - .config-server:rules:deploy-dev
    - .config-server:helm-deploy
  needs:
    - job: config-server:package
      artifacts: true
  environment:
    name: dev/spring-cloud-config-server
  script:
    - |
      if [ -n "${KUBE_CONFIG_DEV:-}" ]; then
        printf '%s' "$KUBE_CONFIG_DEV" > /root/.kube/config
      elif [ -n "${KUBE_CONFIG_DEV_B64:-}" ]; then
        if printf '%s' "$KUBE_CONFIG_DEV_B64" | grep -qE '(^apiVersion:|^kind: Config|^clusters:)'; then
          printf '%s' "$KUBE_CONFIG_DEV_B64" > /root/.kube/config
        elif ! printf '%s' "$KUBE_CONFIG_DEV_B64" | base64 -d > /root/.kube/config; then
          echo "KUBE_CONFIG_DEV_B64 is not valid base64. Set KUBE_CONFIG_DEV to raw kubeconfig or KUBE_CONFIG_DEV_B64 to base64 kubeconfig."
          exit 1
        fi
      else
        echo "KUBE_CONFIG_DEV or KUBE_CONFIG_DEV_B64 must be set."
        exit 1
      fi
    - chmod 600 /root/.kube/config
    - export KUBECONFIG=/root/.kube/config
    - |
      if [ -z "${CONFIG_GIT_TOKEN:-}" ]; then
        echo "CONFIG_GIT_TOKEN must be set as a GitLab CI/CD variable."
        exit 1
      fi
    - kubectl create namespace "$CONFIG_SERVER_K8S_NAMESPACE_DEV" --dry-run=client -o yaml | kubectl apply -f -
    - >
      kubectl create secret generic "$CONFIG_SERVER_GIT_SECRET_NAME"
      --namespace "$CONFIG_SERVER_K8S_NAMESPACE_DEV"
      --from-literal=token="$CONFIG_GIT_TOKEN"
      --dry-run=client
      -o yaml
      | kubectl apply -f -
    - 'export IMAGE_REPOSITORY="${CONFIG_SERVER_IMAGE%:*}"'
    - 'export IMAGE_TAG="${CONFIG_SERVER_IMAGE##*:}"'
    - 'echo "Deploy image: $IMAGE_REPOSITORY:$IMAGE_TAG"'
    - >
      helm upgrade --install "$CONFIG_SERVER_HELM_RELEASE"
      "$CONFIG_SERVER_HELM_CHART_DIR"
      --namespace "$CONFIG_SERVER_K8S_NAMESPACE_DEV"
      --create-namespace
      --values "$CONFIG_SERVER_HELM_CHART_DIR/values.yaml"
      --values "$CONFIG_SERVER_HELM_CHART_DIR/values-dev.yaml"
      --set-string image.repository="$IMAGE_REPOSITORY"
      --set-string image.tag="$IMAGE_TAG"
      --set-string app.configGitUri="$CONFIG_GIT_URI"
      --set-string app.configGitUsername="$CONFIG_GIT_USERNAME"
      --set-string app.configGitDefaultLabel="$CONFIG_GIT_DEFAULT_LABEL"
      --set-string app.configGitSearchPaths="$CONFIG_GIT_SEARCH_PATHS"
      --set-string app.configGitSkipSslValidation="$CONFIG_GIT_SKIP_SSL_VALIDATION"
      --set-string gitTokenSecret.name="$CONFIG_SERVER_GIT_SECRET_NAME"
      --atomic
      --wait
      --timeout 15m
