# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Build, tag, and push the Docker images to the GitLab Docker registry
build slice:
  variables:
    IMAGE_NAME: 'slice' # name of the microservice
    IMAGE_NAME_TEST: 'slice-test' # name of the microservice
    IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
  stage: build
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - docker build -t "$IMAGE_NAME:$IMAGE_TAG" -f ./src/$IMAGE_NAME/Dockerfile ./src/
    - docker tag "$IMAGE_NAME:$IMAGE_TAG" "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
    - docker push "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# Pull, execute, and run unitary tests for the Docker image from the GitLab registry
unit_test slice:
  variables:
    IMAGE_NAME: 'slice' # name of the microservice
    IMAGE_NAME_TEST: 'slice-test' # name of the microservice
    IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
  stage: unit_test
  needs:
    - build slice
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - if docker network list | grep teraflowbridge; then echo "teraflowbridge is already created"; else docker network create -d bridge teraflowbridge; fi  
  script:
    - docker pull "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
    - docker run -d -p 4040:4040 --name $IMAGE_NAME --network=teraflowbridge "$IMAGE_NAME:$IMAGE_TAG"
    - docker ps -a
    - sleep 5
    - docker ps -a
    - docker logs $IMAGE_NAME
    - docker exec -i $IMAGE_NAME bash -c "pytest --log-level=DEBUG --verbose $IMAGE_NAME/tests/test_unitary.py"
  after_script:
    - docker stop $IMAGE_NAME
    - docker rm $IMAGE_NAME
  rules:
    - changes:
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# Deployment of the service in Kubernetes Cluster
deploy slice:
  stage: deploy
  needs:
    - build slice
    - unit_test slice
    - dependencies all
    - integ_test execute
  script:
    - kubectl version
    - kubectl get all
    - kubectl apply -f "manifests/sliceservice.yaml"
    - kubectl delete pods --selector app=sliceservice
    - kubectl get all
