---
variables:
  S3_ENDPOINT: "https://s3.embl.de"
  S3_BUCKET: "annelids"

stages:
  - download_from_s3
  - upload_to_s3
  - build_container
  - deploy_to_cluster
  - clean_up_on_failure

s3_access_test:
  image: minio/mc
  stage: download_from_s3
  before_script:
    - mc alias set genomes $S3_ENDPOINT $S3_ACCESS_KEY $S3_SECRET_KEY
  script:
    - mc ls genomes/$S3_BUCKET
    - cd image

build_nginx_with_jbrowse_config_file:
  image: gcr.io/kaniko-project/executor:debug-v0.21.0
  stage: build_container
  before_script:
    - echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\
    \"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
  script:
    - /kaniko/executor --cache=true --context $CI_PROJECT_DIR/image 
    --dockerfile $CI_PROJECT_DIR/image/Dockerfile 
    --destination $CI_REGISTRY_IMAGE:jbrowse2-$CI_COMMIT_SHORT_SHA

cluster_access_test:
  image: dtzar/helm-kubectl:3.8.2
  stage: deploy_to_cluster
  before_script:
    - cd deployment
    - echo $KUBECONFIG | base64 -d > /tmp/kubeconf
    - export KUBECONFIG=/tmp/kubeconf
  script:
    - kubectl config current-context

kustomize_build_apply:
  image: dtzar/helm-kubectl:3.8.2
  stage: deploy_to_cluster
  before_script:
    - echo $KUBECONFIG | base64 -d > /tmp/kubeconf
    - export KUBECONFIG=/tmp/kubeconf
    - kubectl -n $NS create secret docker-registry gitlab-auth-token
    --docker-server=$CI_REGISTRY --docker-username=$CI_REGISTRY_USER
    --docker-password=$CI_REGISTRY_PASSWORD
  script:
    - kubectl apply -k deployment
    - kubectl -n $NS wait --for=condition=available --timeout=60s deploy/jbrowse2
  dependencies:
    - cluster_access_test

clean_up_k8s_deployment:
  image: dtzar/helm-kubectl:3.8.2
  stage: clean_up_on_failure
  when: on_failure
  before_script:
    - echo $KUBECONFIG | base64 -d > /tmp/kubeconf
    - export KUBECONFIG=/tmp/kubeconf
  script:
    - echo 'Failed job, deleting resources'
    - kubectl delete -k deployment
    - kubectl -n $NS delete secret gitlab-auth-token