stages:
  - build image
  - test image
  - build chart
  - deploy
#  - registry_cleanup
image: docker:19.03.1
variables:
  DOCKER_TLS_CERTDIR: ""
  DOCKER_HOST: "tcp://localhost:2375"
#  DOCKER_TLS_CERTDIR: "/certs"
#  DOCKER_HOST: "tcp://localhost:2376"
  DOCKER_DRIVER: overlay2
  HELM_EXPERIMENTAL_OCI: "1"
services:
  - docker:19.03.1-dind

include:
  - project: 'cspp_geo/geosphere/geosphere-deploy'
    file: '/helpers/docker_base.yaml'
  - project: 'cspp_geo/geosphere/geosphere-deploy'
    file: '/helpers/build_image.yaml'

build_image_tile_gen:
  extends: .build_image
  variables:
    IMAGE_NAME: "tile-gen"
    IMAGE_DIR: "tile_gen"

build_image_mapserver:
  extends: .build_image
  variables:
    IMAGE_NAME: "geosphere-mapserver"
    IMAGE_DIR: "mapserver"

build_chart:
  stage: build chart
  tags:
    - docker
    - kubernetes
  before_script:
    - docker login -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD} ${CI_REGISTRY}
    - alias helm='docker run -t --rm -e HELM_EXPERIMENTAL_OCI="$HELM_EXPERIMENTAL_OCI" -v $(pwd):/apps -w /apps -v ~/.kube:/root/.kube -v ~/.helm:/root/.helm -v ~/.config/helm:/root/.config/helm -v ~/.cache/helm:/root/.cache/helm alpine/helm:3.2.3'
    - helm registry login -u ${CI_REGISTRY_USER} -p ${CI_JOB_TOKEN} ${CI_REGISTRY}
  script:
    - image_url="${CI_REGISTRY_IMAGE}/charts/geosphere-mapserver"
    - if [ -z "$CI_COMMIT_TAG" ]; then
          docker_tag=$CI_COMMIT_SHORT_SHA;
      else
          docker_tag=$CI_COMMIT_TAG;
      fi;
    - chart_tag=$docker_tag
    - cd chart
    - |-
      sed -i "s/^appVersion: .*\$/appVersion: ${docker_tag}/g" geosphere-mapserver/Chart.yaml
    - helm lint geosphere-mapserver
    - helm chart save geosphere-mapserver ${image_url}:${chart_tag}
    - helm chart push ${image_url}:${chart_tag}
  artifacts:
    paths:
      - chart/geosphere-mapserver
    when: on_success
    expire_in: 6 hours

deploy_application:
  stage: deploy
  trigger:
    project: cspp_geo/geosphere/geosphere-deploy
    strategy: depend


#registry_cleanup:
#  stage: registry_cleanup
#  tags:
#    - docker
#  script:
#    - ci/registry_cleanup.sh
