variables:
  GIT_SUBMODULE_STRATEGY: recursive

stages:
  - test
  - build
  - deploy

zola check:
  stage: test
  image: alpine:latest
  before_script:
  - apk add --update-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ zola
  - apk add yarn
  - yarn install
  script:
  - zola check

.build:
  stage: build
  interruptible: true
  image:
    name: gcr.io/kaniko-project/executor:debug
    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_NAME
       --digest-file DIGESTFILE
       --build-arg BASE_URL=$BASE_URL
       --cache=true
       --cleanup
  artifacts:
    paths:
      - DIGESTFILE


build production:
  extends: .build
  variables:
    BASE_URL: https://teckids.org
  only:
    - master

build review:
  extends: .build
  variables:
    BASE_URL: https://$CI_COMMIT_REF_SLUG.review.teckids.org
  only:
    - merge_requests

.deploy:
  stage: deploy
  image: line/kubectl-kustomize:latest
  tags:
    - teckids-trusted
  before_script:
    - echo $KUBECONFIG | base64 -d > /tmp/kubeconfig

deploy production:
  extends: .deploy
  environment:
    name: production
    url: https://teckids.org
  script:
    - cd deploy/overlays/production
    - kustomize edit set image registry.edugit.org/teckids/team-pr/teckids.org:$CI_COMMIT_REF_NAME@$(cat ../../../DIGESTFILE)
    - kustomize build > output.yaml
    - kubectl --kubeconfig=/tmp/kubeconfig apply -f output.yaml
  only:
    - master

deploy review:
  extends: .deploy
  script: deploy_review
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: https://$CI_COMMIT_REF_SLUG.review.teckids.org
    on_stop: delete review
    auto_stop_in: 3 days
  only:
    - merge_requests
  when: manual
  script:
    - cd deploy/overlays/review
    - kustomize edit set image registry.edugit.org/teckids/team-pr/teckids.org:$CI_COMMIT_REF_NAME@$(cat ../../../DIGESTFILE)
    - kustomize edit set nameprefix $CI_COMMIT_REF_SLUG
    - kustomize build | sed s/__REVIEW_NAME__/$CI_COMMIT_REF_SLUG/g > output.yaml
    - kubectl --kubeconfig=/tmp/kubeconfig apply -f output.yaml

delete review:
  extends: .deploy
  script: delete_review
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    action: stop
  before_script:
    - echo $KUBECONFIG | base64 -d > /tmp/kubeconfig
    - cd deploy/overlays/review
    - kustomize edit set image registry.edugit.org/teckids/team-pr/teckids.org:$CI_COMMIT_REF_NAME@$(cat ../../../DIGESTFILE)
    - kustomize edit set nameprefix $CI_COMMIT_REF_SLUG
    - kustomize build | sed s/__REVIEW_NAME__/$CI_COMMIT_REF_SLUG/g > output.yaml
  script:
    - kubectl --kubeconfig=/tmp/kubeconfig delete -f output.yaml
  when: manual
  only:
    - merge_requests
