image: docker:latest

.runner_tags: &runner_tags
  tags:
    - dind

services:
  - docker:dind

variables:
  CONTAINER_TEST_IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME"
  CONTAINER_RELEASE_IMAGE: "$CI_REGISTRY_IMAGE:latest"
  CONTAINER_TAG_IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG"

stages:
  - build
  - test
  - release

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

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

test:
  <<: *runner_tags
  stage: test
  before_script:
    - apk add --update py-pip
    - pip install docker-compose
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - docker pull "$CONTAINER_TEST_IMAGE"
    - docker-compose -f docker-compose.yml up -d postgres redis
    - sleep 5
    - docker-compose -f docker-compose.yml run --rm web
  after_script:
    - docker rm -f csentry_postgres
    - docker rm -f csentry_redis

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