# Kaniko is used for building images in kubernetes.
# For more information see: https://docs.gitlab.com/ee/ci/docker/using_kaniko.html
build:
  stage: build
  image:
    name: gcr.io/kaniko-project/executor:debug
    # entrypoint needs to be overridden see: https://docs.gitlab.com/ee/ci/docker/using_kaniko.html
    entrypoint: [""]
  script:
    - echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
    - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/Dockerfile --destination $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
  tags:
    - kubernetes

upload Helm Chart:
  stage: build
  image: alpine/helm:3.5.3
  rules:
    - if: $CI_MERGE_REQUEST_ID
      when: never
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: on_success
      variables:
        TAG_NAME: stable
    - if: '$CI_COMMIT_BRANCH == "develop"'
      when: on_success
      variables:
        TAG_NAME: latest
  script:
    - HELM_TAG=$(grep -E -o "(version:)(.*)" helm/manifest-service/Chart.yaml | sed -E 's/.*version:[[:space:]](.*)/\1/g')
    - export HELM_EXPERIMENTAL_OCI=1
    - helm registry login registry.open-xchange.com -u "$OX_REGISTRY_USER" -p "$OX_REGISTRY_TOKEN"
    - helm chart save helm/manifest-service registry.open-xchange.com//frontend/manifest-service:$TAG_NAME
    - helm chart save helm/manifest-service registry.open-xchange.com//frontend/manifest-service
    - helm chart push registry.open-xchange.com//frontend/manifest-service:$TAG_NAME
    - helm chart push registry.open-xchange.com//frontend/manifest-service:$HELM_TAG
  tags:
    - kubernetes


# Helm is used for deploying everything to kubernetes
# Afterwards we do a rolling restart of our deployment
deploy:
  stage: deploy
  image: dtzar/helm-kubectl
  tags:
    - kubernetes
  script:
    - envsubst < helm/values/develop.yaml > values.yaml
    - kubectl create secret docker-registry gitlab-registry-credentials --docker-server=$CI_REGISTRY --docker-username=$GITLAB_DEPLOY_USER --docker-password=$GITLAB_DEPLOY_PASSWORD --dry-run=client -o yaml | kubectl apply -f -
    - helm upgrade -i manifest-service helm/manifest-service -f values.yaml
    - kubectl rollout restart deployment manifest-service
  environment:
    name: $CI_COMMIT_REF_SLUG
    url: https://manifest-$CI_COMMIT_REF_SLUG.k3s.os.oxui.de/
  only:
    - main
