variables:
    GIT_SUBMODULE_STRATEGY: recursive

stages:
    - build
    - test
    - build_kubernetes_dev
    - build_kubernetes
    - deploy


build:
    image:
        name: gradle:jdk21-alpine
    stage: build
    script:
        - sh $CI_PROJECT_DIR/gradlew assemble

test:
    image:
        name: gradle:jdk21-alpine
    stage: test
    script:
        - sh $CI_PROJECT_DIR/gradlew test -Dspring.profiles.active=test
    #        - sh $CI_PROJECT_DIR/gradlew detekt
    dependencies:
        - build

.base:
    image:
        name: gcr.io/kaniko-project/executor:v1.23.2-debug
        entrypoint: [""]
    cache: {}
    before_script:
        - echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json

build_sha_dev:
    extends: .base
    stage: build_kubernetes_dev
    only:
        - dev
    script:
        - /kaniko/executor --build-arg "profile=dev" --context "${CI_PROJECT_DIR}" --dockerfile "${CI_PROJECT_DIR}/Dockerfile" --destination "${CI_REGISTRY_IMAGE}:dev_${CI_COMMIT_SHORT_SHA}"

build_sha_prod:
    extends: .base
    stage: build_kubernetes
    only:
        - main
    script:
        - /kaniko/executor --build-arg "profile=prod" --context "${CI_PROJECT_DIR}" --dockerfile "${CI_PROJECT_DIR}/Dockerfile" --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}" --destination "${CI_REGISTRY_IMAGE}:latest"

deploy_development:
    image: bitnami/kubectl:1.30-debian-12
    before_script:
        - export KUBECONFIG=$KUBECONFIG_FILE
    stage: deploy
    only:
        - dev
    script:
        - |-
            set -x
            kubectl --namespace=fraunhofer apply -f ./kubernetes/configmap.yaml
            kubectl --namespace=fraunhofer set image -f ./kubernetes/deployment.yaml "b-container=registry.opencode.de/opencode-analyzer/data-provider:dev_${CI_COMMIT_SHORT_SHA}" --local -o yaml | kubectl --namespace=fraunhofer apply -f -
            kubectl --namespace=fraunhofer apply -f ./kubernetes/service.yaml
            kubectl --namespace=fraunhofer rollout status -f ./kubernetes/deployment.yaml --watch=true --timeout 300s || (
                kubectl --namespace=fraunhofer rollout undo -f ./kubernetes/deployment.yaml
                exit 1
            )

deploy_production:
    image: bitnami/kubectl:1.30-debian-12
    before_script:
        - export KUBECONFIG=$KUBECONFIG_FILE
    stage: deploy
    only:
        - main
    script:
        - |-
            set -x
            kubectl --namespace=fraunhoferprod apply -f ./kubernetes/configmap-prod.yaml
            kubectl --namespace=fraunhoferprod set image -f ./kubernetes/deployment-prod.yaml b-container=registry.opencode.de/opencode-analyzer/data-provider:${CI_COMMIT_SHORT_SHA} --local -o yaml | kubectl --namespace=fraunhoferprod apply -f -
            kubectl --namespace=fraunhoferprod apply -f ./kubernetes/service.yaml
        # XXX add rollout undo if tested on dev