workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: always
    - if: >-
        $CI_PIPELINE_SOURCE == "push"
        && ($CI_COMMIT_BRANCH == "staging" || $CI_COMMIT_BRANCH == "master")
      when: always
    - when: never

variables:
  DOCKER_VERSION: '20.10.12'
  K8S_NAMESPACE: 'devops-s22-deployable'
  CONTAINER_TAG: '${CI_REGISTRY_IMAGE}:${CI_PIPELINE_IID}-${CI_COMMIT_SHORT_SHA}'

stages:
  - test
  - build
  - deploy

job_test-image:
  stage: test
  tags:
    - docker-priviliged
  image: docker:$DOCKER_VERSION
  services:
    - name: docker:$DOCKER_VERSION-dind
  script:
    - docker build
      --tag "${CONTAINER_TAG}-test"
      --target=test
      "./"
  after_script:
    - docker image rm --force "${CI_REGISTRY_IMAGE}:${CI_PIPELINE_IID}-${CI_COMMIT_SHORT_SHA}"

job_build-image:
  stage: build
  needs:
    - 'job_test-image'
  rules:
    - if: $CI_COMMIT_BRANCH != "staging" && $CI_COMMIT_BRANCH != "master"
      when: 'never'
  tags:
    - docker-priviliged
  image: docker:$DOCKER_VERSION
  services:
    - name: docker:$DOCKER_VERSION-dind
  script:
    - SERVER_PUBLIC_URL=""
    - DB_HOST=""
    - docker build
      --tag "${CONTAINER_TAG}"
      --build-arg JWT_SECRET=${JWT_SECRET}
      --build-arg SERVER_PUBLIC_URL=${SERVER_PUBLIC_URL}
      --build-arg DB_HOST=${DB_HOST}
      "./"
    - docker login -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD} ${CI_REGISTRY}
    - docker push "${CI_REGISTRY_IMAGE}:${CI_PIPELINE_IID}-${CI_COMMIT_SHORT_SHA}"
  after_script:
    - docker image rm --force "${CI_REGISTRY_IMAGE}:${CI_PIPELINE_IID}-${CI_COMMIT_SHORT_SHA}"

job_deploy-image:
  stage: deploy
  needs:
    - 'job_build-image'
  rules:
    - if: $CI_COMMIT_REF_NAME =~ /staging/
      when: 'always'
      variables:
        ENVIRONMENT_NAME: 'staging'
    - if: $CI_COMMIT_REF_NAME !~ /staging/
      when: 'always'
      variables:
        ENVIRONMENT_NAME: 'prod'
  tags:
    - docker
  image:
    name: k8s-image
    entrypoint: ['']
  script:
    # - IMAGE="${CI_REGISTRY_IMAGE}:${VERSION}"
    - kubectl apply
        --kubeconfig ${SECRET_KUBECONFIG_PATH}
        --namespace "${ENVIRONMENT_NAME}-${K8S_NAMESPACE}"
        --kustomize -



