stages:
        - build
        - test
        - pages
        - staging

variables:
        IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME

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

# ============================== Testing section ============================= #
# ----------------------------- Backend subsection --------------------------- #
.test_template_backend: &test_definition_backend
        stage: test
        image: $IMAGE_TAG
        before_script:
                - cd backend/

test_pytest:
        <<: *test_definition_backend
        services:
                - postgres:9.5
        script:
                - DJANGO_SETTINGS_MODULE=grady.settings pytest --cov
        artifacts:
                paths:
                        - .coverage

test_prospector:
        <<: *test_definition_backend
        script:
                - prospector --uses django || exit 0

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

test_frontend:
        <<: *test_definition_frontend
        script:
                - yarn install
                - yarn test --single-run

# ============================ Gitlab pages section =========================== #
test_coverage:
        <<: *test_definition_backend
        stage:
                pages
        script:
                - mkdir public
                - coverage html
        dependencies:
                - test_pytest
        artifacts:
                paths:
                        - public

# ============================== Staging section ============================= #
.staging_template: &staging_definition
        stage: staging
        image: docker:latest
        only:
                - master

staging:
        <<: *staging_definition
        environment:
                name: review/$CI_COMMIT_REF_NAME
                url: https://staging.grady.janmax.org
                on_stop: staging_stop
        script:
                - apk add --update py-pip && pip install docker-compose
                - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
                - docker-compose pull
                - docker-compose up -d --build

staging_stop:
        <<: *staging_definition
        script:
                - apk add --update py-pip && pip install docker-compose
                - docker-compose rm --force --stop
        when: manual
        environment:
                name: review/$CI_COMMIT_REF_NAME
                action: stop