variables:
  IMAGE_NAME: 'monitoring' # name of the microservice
  IMAGE_NAME_TEST: 'monitoring-test' # name of the microservice
  IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)

# build the Docker image
build monitoring:
  stage: build
  script:
    - docker build -t "$IMAGE_NAME:$IMAGE_TAG" -f ./src/$IMAGE_NAME/Dockerfile ./src/
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# tags the Docker image
tag monitoring:
  stage: build
  script:
    - docker tag "$IMAGE_NAME:$IMAGE_TAG" "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# push the Docker image to the gitlab Docker registry
push monitoring:
  stage: build
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - docker push "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml


# test if the Docker image can be pulled from the gitlab registry
test monitoring pull:
  stage: test
  needs:
    - push monitoring
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - docker pull "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# test if the Docker image can be executed
test monitoring run:
  stage: test
  needs:
    - build monitoring
  before_script:
    - if docker network list | grep teraflowbridge; then echo "teraflowbridge is already created"; else docker network create -d bridge teraflowbridge; fi  
  script:
    - docker run -d -p 7070:7070 --name monitoring --network=teraflowbridge --rm "$IMAGE_NAME:$IMAGE_TAG"
    - docker ps > deploy_test_report.txt
  after_script:
    - docker stop monitoring
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml
  artifacts:
    when: always
    paths:
      - deploy_test_report.txt
    expire_in: 1 day

# apply unit test to the monitoring component
test monitoring pytest:
  stage: test
  needs:
    - build monitoring
  script:
    - docker build -t "$IMAGE_NAME_TEST:$IMAGE_TAG" -f ./src/$IMAGE_NAME/tests/Dockerfile ./src/ > pytest_report.txt
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml
  artifacts:
      when: always
      paths:
        - pytest_report.txt
      expire_in: 1 day

# Deployment of the monitoring service in Kubernetes Cluster
deploy monitoring:
  stage: deploy
  needs:
    - build monitoring
    - test monitoring run
  script:
    - kubectl version
    - kubectl get all
    - kubectl apply -f "manifests/monitoringservice.yaml"
    - kubectl get all
  when: manual


