image: docker:latest

.runner_tags: &runner_tags
  tags:
    - docker

variables:
  CONTAINER_TEST_IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME"
  CONTAINER_RELEASE_IMAGE: "$CI_REGISTRY_IMAGE:latest"
  CONTAINER_CACHE_IMAGE: "$CI_REGISTRY_IMAGE:master"
  POSTGRES_USER: ics
  POSTGRES_PASSWORD: icspwd
  POSTGRES_DB: csentry_db_test

stages:
  - build
  - test
  - release
  - deploy

before_script:
  - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY

build:
  <<: *runner_tags
  stage: build
  script:
    - docker pull "$CONTAINER_CACHE_IMAGE" || true
    - docker build --pull --cache-from "$CONTAINER_CACHE_IMAGE" -t "$CONTAINER_TEST_IMAGE" .
    - docker push "$CONTAINER_TEST_IMAGE"

test:
  <<: *runner_tags
  stage: test
  image: "$CONTAINER_TEST_IMAGE"
  services:
    - postgres:10
    - redis:4.0
  before_script: []
  script:
    - pytest --cov=app -v

release-image:
  <<: *runner_tags
  stage: release
  script:
    - docker pull "$CONTAINER_TEST_IMAGE"
    - docker tag "$CONTAINER_TEST_IMAGE" "$CONTAINER_RELEASE_IMAGE"
    - docker push "$CONTAINER_RELEASE_IMAGE"
  only:
    - tags

deploy-staging:
  <<: *runner_tags
  stage: deploy
  before_script:
    - apk add --update curl
    - curl -s -o /tmp/functions.sh ${ICS_SHARED_GITLAB_CI_FUNCTIONS}
    - . /tmp/functions.sh
  script:
    - launch_job_template deploy-csentry-staging
  only:
    - tags
