---
include:
  - remote: "https://gitlab.esss.lu.se/ics-infrastructure/gitlab-ci-yml/raw/master/PreCommit.gitlab-ci.yml"
  - remote: "https://gitlab.esss.lu.se/ics-infrastructure/gitlab-ci-yml/raw/master/SonarScanner.gitlab-ci.yml"

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:
  - check
  - build
  - test
  - analyse
  - release
  - deploy

default:
  tags:
    - docker

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

build:
  stage: build
  image: docker:latest
  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:
  stage: test
  image: "$CONTAINER_TEST_IMAGE"
  services:
    - postgres:10
    - redis:4.0
    - name: docker.elastic.co/elasticsearch/elasticsearch:7.3.2
      alias: elasticsearch
      command: ["bin/elasticsearch", "-Ediscovery.type=single-node"]
  before_script:
    - pip install -r requirements-dev.txt
  script:
    - pytest --junitxml=junit.xml --cov-report=xml:coverage.xml --cov-report=term --cov=app -v
  artifacts:
    paths:
      - junit.xml
      - coverage.xml
    reports:
      junit: junit.xml
    expire_in: 1 hour

release-image:
  stage: release
  image: docker:latest
  dependencies: []
  script:
    - docker pull "$CONTAINER_TEST_IMAGE"
    - docker tag "$CONTAINER_TEST_IMAGE" "$CONTAINER_RELEASE_IMAGE"
    - docker push "$CONTAINER_RELEASE_IMAGE"
  only:
    - tags

deploy-staging:
  stage: deploy
  image: registry.esss.lu.se/ics-docker/tower-cli
  before_script: []
  dependencies: []
  script:
    - >
      tower-cli job launch
      -h torn.tn.esss.lu.se
      -t ${TOWER_OAUTH_TOKEN}
      -J deploy-csentry-staging
      -e "csentry_tag=$CI_COMMIT_REF_NAME" --monitor
  environment:
    name: staging
    url: https://csentry-test.esss.lu.se
  only:
    - master
    - tags

pages:
  stage: deploy
  image: "$CONTAINER_RELEASE_IMAGE"
  dependencies: []
  before_script:
    - pip install -r requirements-dev.txt
  script:
    - sphinx-build -M html docs docs/_build
    - mv docs/_build/html public
  artifacts:
    paths:
      - public
  # CI_COMMIT_TAG is used in docs/conf.py
  # Don't forget to update if not only deploying docs for tags
  only:
    - tags

deploy-production:
  stage: deploy
  image: registry.esss.lu.se/ics-docker/tower-cli
  before_script: []
  dependencies: []
  script:
    - >
      tower-cli job launch
      -h torn.tn.esss.lu.se
      -t ${TOWER_OAUTH_TOKEN}
      -J deploy-csentry
      -e "csentry_tag=$CI_COMMIT_TAG" --monitor
  environment:
    name: production
    url: https://csentry.esss.lu.se
  only:
    - tags
  when: manual
