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

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

# Run integration tests in Kubernetes Cluster
integration_test integration_tester:
  variables:
    IMAGE_NAME: 'integration_tester' # name of the microservice
    IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
  stage: integration_test
  needs:
    - build integration_tester
    - test integration_tester
    - deploy context
    - deploy device
    - dependencies all
  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
    # --rm to remove tester when it finishes
    - kubectl run $(echo $IMAGE_NAME | sed -r 's/[^a-zA-Z0-9\.\-]/-/g') --image "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG" --restart=Never -i
    - kubectl get all
  #when: manual
  #allow_failure: false
