workflow:
  rules:
    # NOTE: don't run pipeline if commit is a Merge/Pull-Request
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: "never"
    # Otherwise:
    - when: "always"

image: node:12.16.3

stages:
  - test
  - build
  - deploy

variables:
  MONGODB_VERSION: "4.2.6"
  MONGODB_URL: "mongodb://mongodb:27017/test"
  PORT: "3002"
  JWT_SECRET: "test"

# http://docs.gitlab.com/ee/ci/yaml/README.html#cache
cache:
  paths:
    - app/client/node_modules/
    - app/server/node_modules/

test_client:
  stage: test
  script:
    - cd app/client
    - npm install
    - npm run test
  when: always

test_server:
  stage: test
  # Info: http://docs.gitlab.com/ee/ci/docker/using_docker_images.html#what-is-a-service
  services:
    - name: mongo:$MONGODB_VERSION
      alias: mongodb
  script:
    - cd app/server
    - npm install
    - npm run test
  when: always

build:
  stage: build
  needs:
    - test_client
    - test_server
  tags:
    - docker-privileged
  # Deactivate filter for testing purposes
  # rules:
  #   - if: $CI_COMMIT_TAG
  #     when: always
  image: docker:19.03.12
  services:
    - docker:19.03.12-dind
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  variables:
    IMAGE_TAG: "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}-${CI_COMMIT_TAG}"
    RELEASE_IMAGE_TAG: "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}-${CI_PIPELINE_IID}:latest"
  script:
    - docker build -t $IMAGE_TAG .
    - docker tag $IMAGE_TAG $RELEASE_IMAGE_TAG
    - docker push $IMAGE_TAG
    - docker push $RELEASE_IMAGE_TAG
  after_script:
    - docker image rm --force $IMAGE_TAG
# clean_docker_registry:
#   stage: build
#   tags:
#     - docker-privileged
#   when: always
#   image: docker:19.03.12
#   services:
#     - docker:19.03.12-dind
#   before_script:
#     - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
#   script:
#     - docker image ls -a
#     - docker image prune
