name: e2e-k3s

on:
  pull_request:
    types: [labeled]

jobs:

  e2e-k3s:
    runs-on: ubuntu-latest
    if: ${{ github.event.label.name == 'ok-to-test' }}
    env:
      DOCKER_TAG: pull-${{ github.event.number }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Build query-service image
        env:
          DEV_BUILD: 1
        run: make build-ee-query-service-amd64

      - name: Build frontend image
        run: make build-frontend-amd64

      - name: Create a k3s cluster
        uses: AbsaOSS/k3d-action@v2
        with:
          cluster-name: "signoz"

      - name: Inject the images to the cluster
        run: k3d image import signoz/query-service:$DOCKER_TAG signoz/frontend:$DOCKER_TAG -c signoz

      - name: Set up HotROD sample-app 
        run: |
          # create sample-application namespace
          kubectl create ns sample-application

          # apply hotrod k8s manifest file
          kubectl -n sample-application apply -f https://raw.githubusercontent.com/SigNoz/signoz/main/sample-apps/hotrod/hotrod.yaml

          # wait for all deployments in sample-application namespace to be READY
          kubectl -n sample-application get deploy --output name | xargs -r -n1 -t kubectl -n sample-application rollout status --timeout=300s

      - name: Deploy the app
        run: |
          # add signoz helm repository
          helm repo add signoz https://charts.signoz.io

          # create platform namespace
          kubectl create ns platform

          # installing signoz using helm
          helm install my-release signoz/signoz -n platform \
            --wait \
            --timeout 10m0s \
            --set frontend.service.type=LoadBalancer \
            --set queryService.image.tag=$DOCKER_TAG \
            --set frontend.image.tag=$DOCKER_TAG

          # get pods, services and the container images
          kubectl get pods -n platform
          kubectl get svc -n platform

      - name: Kick off a sample-app workload
        run: |
          # start the locust swarm
          kubectl -n sample-application run strzal --image=djbingham/curl \
            --restart='OnFailure' -i --rm --command -- curl -X POST -F \
            'locust_count=6' -F 'hatch_rate=2' http://locust-master:8089/swarm

      - name: Get short commit SHA and display tunnel URL
        id: get-subdomain
        run: |
          subdomain="pr-$(git rev-parse --short HEAD)"
          echo "URL for tunnelling: https://$subdomain.loca.lt"
          echo "::set-output name=subdomain::$subdomain"

      - name: Start tunnel
        env:
          SUBDOMAIN: ${{ steps.get-subdomain.outputs.subdomain }}
        run: |
          npm install -g localtunnel
          host=$(kubectl get svc -n platform | grep frontend | tr -s ' ' | cut -d" " -f4)
          port=$(kubectl get svc -n platform | grep frontend | tr -s ' ' | cut -d" " -f5 | cut -d":" -f1)
          lt -p $port -l $host -s $SUBDOMAIN
