stages:
  - build
  - test
  - build_image
  - pages
  - staging

variables:
  IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME


# ========================== Build Testing section =========================== #
build_test_env:
  image: python:3.6
  stage: build
  script:
    - python -m venv .venv
    - source .venv/bin/activate
    - make install
  artifacts:
    paths:
      - .venv/
    expire_in: 20 minutes
  cache:
    key: "$CI_JOB_NAME"
    paths:
      - .venv

# ============================== Testing section ============================= #
# ----------------------------- Backend subsection --------------------------- #
.test_template_virtualenv: &test_definition_virtualenv
  image: python:3.6
  before_script:
    - source .venv/bin/activate
  dependencies:
    - build_test_env

test_pytest:
  <<: *test_definition_virtualenv
  stage: test
  services:
    - postgres:9.5
  script:
    - pytest --cov --ds=grady.settings.test core/tests
  artifacts:
    paths:
      - .coverage
  cache:
    key: "$CI_JOB_NAME"
    paths:
      - .coverage

test_flake8:
  <<: *test_definition_virtualenv
  stage: test
  script:
    - flake8 --exclude=migrations core util

# ----------------------------- Frontend subsection -------------------------- #
.test_template_frontend: &test_definition_frontend
  image: node:carbon
  before_script:
    - cd frontend/

test_frontend:
  <<: *test_definition_frontend
  when: manual
  stage: test
  script:
    - yarn install
    - yarn test --single-run
  cache:
    key: "$CI_JOB_NAME"
    paths:
      - frontend/node_modules/

# =========================== Build Image section ============================ #
build_backend:
  image: docker:latest
  stage: build_image
  script:
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker build -t $IMAGE_TAG .
    - docker tag $IMAGE_TAG $IMAGE_TAG-$CI_COMMIT_SHA
    - docker push $IMAGE_TAG

# =========================== Gitlab pages section =========================== #
pages:
  <<: *test_definition_virtualenv
  stage:
    pages
  script:
    - coverage html -d public
  dependencies:
    - test_pytest
    - build_test_env
  artifacts:
    paths:
      - public
  only:
    - master

# ============================== Staging section ============================= #
.staging_template: &staging_definition
   image: docker:latest
   only:
     - master
   before_script:
     - apk add --update py-pip && pip install docker-compose

staging:
  <<: *staging_definition
  environment:
    name: review/$CI_COMMIT_REF_NAME
    url: https://staging.grady.janmax.org
    on_stop: staging_stop
  script:
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker-compose stop
    - docker-compose pull
    - docker-compose up -d --force-recreate

staging_stop:
  <<: *staging_definition
  script:
    - docker-compose rm --force --stop
  when: manual
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop
