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
  - analyse
  - 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 --junitxml=junit.xml --cov-report xml:coverage.xml --cov=app -v
  artifacts:
    paths:
      - junit.xml
      - coverage.xml
    expire_in: 1 hour

analyse:
  <<: *runner_tags
  stage: analyse
  image: registry.esss.lu.se/ics-docker/sonar-scanner:3
  before_script: []
  script:
    - sonar-scanner -Dsonar.login=$SONARQUBE_TOKEN -Dsonar.projectVersion=$CI_COMMIT_REF_NAME

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
  image: registry.esss.lu.se/ics-docker/tower-cli:3.2
  before_script: []
  script:
    - >
      tower-cli job launch
      -h torn.tn.esss.lu.se
      -u ${ANSIBLE_AWX_USERNAME}
      -p ${ANSIBLE_AWX_PASSWORD}
      -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:
  <<: *runner_tags
  stage: deploy
  image: "$CONTAINER_RELEASE_IMAGE"
  before_script: []
  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:
  <<: *runner_tags
  stage: deploy
  image: registry.esss.lu.se/ics-docker/tower-cli:3.2
  before_script: []
  script:
    - >
      tower-cli job launch
      -h torn.tn.esss.lu.se
      -u ${ANSIBLE_AWX_USERNAME}
      -p ${ANSIBLE_AWX_PASSWORD}
      -J deploy-csentry
      -e "csentry_tag=$CI_COMMIT_TAG" --monitor
  environment:
    name: production
    url: https://csentry.esss.lu.se
  only:
    - tags
  when: manual
