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_client:
  stage: build
  tags: 
    - docker-privileged
  image: docker:19.03.12
  rules:
    - if: $CI_COMMIT_TAG
      when: always
  services:
    - docker:19.03.12-dind
  before_script: 
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  variables: 
    CLIENT_IMAGE_TAG: registry.beuth-hochschule.de/devops-project/todo-application/client:$CI_COMMIT_TAG
    CLIENT_RELEASE_IMAGE_TAG: registry.beuth-hochschule.de/devops-project/todo-application/client:latest
  script:
    - cd app/client
    - docker build -t $CLIENT_IMAGE_TAG .
    - docker tag $CLIENT_IMAGE_TAG $CLIENT_RELEASE_IMAGE_TAG
    - docker push $CLIENT_IMAGE_TAG
    - docker push $CLIENT_RELEASE_IMAGE_TAG

build_server:
  stage: build
  tags: 
    - docker-privileged
  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: 
    SERVER_IMAGE_TAG: registry.beuth-hochschule.de/devops-project/todo-application/server:$CI_COMMIT_TAG
    SERVER_RELEASE_IMAGE_TAG: registry.beuth-hochschule.de/devops-project/todo-application/server:latest
  script:
    - cd app/server
    - docker build -t $SERVER_IMAGE_TAG .
    - docker tag $SERVER_IMAGE_TAG $SERVER_RELEASE_IMAGE_TAG
    - docker push $SERVER_IMAGE_TAG
    - docker push $SERVER_RELEASE_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
