# Package application needed to run tests & build the image on next stage
build automation:
  variables:
    IMAGE_NAME: 'automation' # name of the microservice
    IMAGE_TAG: '0.0.1' # tag of the container image (production, development, etc)
  stage: build
  script:
    - docker build -t "$IMAGE_NAME:$IMAGE_TAG" -f ./src/$IMAGE_NAME/src/main/docker/Dockerfile.multistage.jvm ./src/$IMAGE_NAME/ --target builder
  after_script:
    - docker images --filter="dangling=true" --quiet | xargs -r docker rmi
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "develop"'
    - changes:
        - src/$IMAGE_NAME/**
        - manifests/${IMAGE_NAME}service.yaml
        - .gitlab-ci.yml

# Run tests, build & push the image
unit_test automation:
  variables:
    IMAGE_NAME: 'automation' # name of the microservice
    IMAGE_TAG: '0.0.1' # tag of the container image (production, development, etc)
  stage: unit_test
  needs:
    - build automation
  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/src/main/docker/Dockerfile.multistage.jvm ./src/$IMAGE_NAME/ --target unit-test
    - docker build -t "$IMAGE_NAME:$IMAGE_TAG" -f ./src/$IMAGE_NAME/src/main/docker/Dockerfile.multistage.jvm ./src/$IMAGE_NAME/ --target release
    - docker tag "$IMAGE_NAME:$IMAGE_TAG" "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
    - docker push "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
  after_script:
    - docker rm -f $IMAGE_NAME
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "develop"'
    - changes:
        - src/$IMAGE_NAME/**
        - manifests/${IMAGE_NAME}service.yaml
        - .gitlab-ci.yml

# Deployment of automation service in Kubernetes Cluster
deploy automation:
  stage: deploy
  needs:
    - build automation
    - unit_test automation
  script:
    - kubectl version
    - kubectl get all
    - kubectl apply -f "manifests/automationservice.yaml"
    - kubectl delete pods --selector app=automationservice
    - kubectl get all
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
      when: manual    
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "develop"'
      when: manual

