variables:
    GIT_SUBMODULE_STRATEGY: recursive

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

version_bump:
    stage: version_bump
    image: python:3
    before_script:
        - pip install bump-my-version
        - git config --global user.email "no-reply@opencode.de"
        - git config --global user.name "CICD Pipeline"
    script:
        # Determine the bump type based on commit messages
        - |
            bump_type="patch"
            if git log $(git describe --tags --abbrev=0)..HEAD --grep="BREAKING CHANGE" --oneline | grep -q "BREAKING CHANGE"; then
                bump_type="major"
            elif git log $(git describe --tags --abbrev=0)..HEAD --grep="feat" --oneline | grep -q "feat"; then
                bump_type="minor"
            fi
        - bump-my-version bump --commit --tag $bump_type VERSION
        - git push --follow-tags https://git:$CI_PUSH_TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH.git HEAD:$CI_COMMIT_REF_NAME

    only:
        - main

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 ktfmtCheck 
    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
    script:
        - ./kubernetes/scripts/deploy.sh "dev" "${CI_COMMIT_SHORT_SHA}" "${CI_DEPLOY_USER} requested to deploy ${CI_COMMIT_BRANCH} ${CI_COMMIT_SHA}"
    when: manual

deploy_production:
    image: bitnami/kubectl:1.30-debian-12
    before_script:
        - export KUBECONFIG=$KUBECONFIG_FILE
    stage: deploy
    script:
        - ./kubernetes/scripts/deploy.sh "prod" "${CI_COMMIT_SHORT_SHA}" "${CI_DEPLOY_USER} requested to deploy ${CI_COMMIT_BRANCH} ${CI_COMMIT_SHA}"
    when: manual