# Build, tag, and push the Docker images to the GitLab Docker registry
build funct_test:
  variables:
    IMAGE_NAME: 'tester_functional' # 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/common/**
      - src/context/**
      - src/device/**
      - src/service/**
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# Pull, execute, and run unitary tests for the Docker image from the GitLab registry
unit_test funct_test:
  variables:
    IMAGE_NAME: 'tester_functional' # name of the microservice
    IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
  stage: test
  needs:
    - build funct_test
  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/common/**
      - src/context/**
      - src/device/**
      - src/service/**
      - src/$IMAGE_NAME/**
      - .gitlab-ci.yml

# Run functional tests in Kubernetes Cluster
funct_test execute:
  variables:
    IMAGE_NAME: 'tester_functional' # name of the microservice
    IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
  stage: funct_test
  needs:
    - build funct_test
    - unit_test funct_test
    - deploy context
    - deploy device
    - deploy service
    - dependencies all
    - integ_test execute
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - kubectl version
    - kubectl get all
    - kubectl delete pod $(echo $IMAGE_NAME | sed -r 's/[^a-zA-Z0-9\.\-]/-/g') --wait=true --ignore-not-found=true
    - kubectl get all
    - kubectl run $(echo $IMAGE_NAME | sed -r 's/[^a-zA-Z0-9\.\-]/-/g') --image "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG" --restart=Never -i --rm
    - kubectl get all
  #when: manual
  #allow_failure: false
