name: Benchmark

on:
  pull_request:
  push:

jobs:
  benchmark:
    name: Benchmark
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: denoland/setup-deno@main
        with:
          deno-version: v1.x

        # this is the performance benchmark
      - name: Cache deps
        run: deno cache performance/mod.ts
      - name: Download sysbench
        run: sudo apt-get install -y sysbench
      - name: Run Benchmark
        run: NO_COLOR=true deno bench --unstable -A performance/mod.ts | tee output.txt
      - name: Format Benchmark Output
        run: deno run --unstable -A performance/tranformOutput.ts

        # this is the memory benchmark
      - name: Download db from benchmark repo
        run: wget https://github.com/discordeno/benchmarks/raw/main/db.tar.gz
      - name: Decompress db
        run: tar -xzvf db.tar.gz
      - name: Run memory benchmark
        run: deno run --v8-flags="--expose-gc" -A performance/memory.ts

      - name: Download previous benchmark data
        uses: actions/cache@v3
        with:
          path: ./benchmarksResult
          key: ${{ github.ref }}-benchmark
      - name: Store benchmark result to cache
        uses: benchmark-action/github-action-benchmark@v1
        with:
          tool: "customSmallerIsBetter"
          output-file-path: output.txt
          external-data-json-path: benchmarksResult/data.json
      - uses: actions/upload-artifact@v3
        with:
          name: benchmarkResults
          path: benchmarksResult/data.json

      - name: Store benchmark result (Main)
        uses: benchmark-action/github-action-benchmark@v1
        if: ${{ github.ref == 'refs/heads/main' }}
        with:
          tool: "customSmallerIsBetter"
          output-file-path: output.txt
          gh-pages-branch: "benchies"
          benchmark-data-dir-path: benchmarksResult
          github-token: ${{ secrets.GITHUB_TOKEN }}
          auto-push: true

      - name: Save Commmit SHA
        run: |
          mkdir -p ./commitData
          echo ${{ github.event.pull_request.head.sha }} > ./commitData/sha
          echo ${{ github.event.pull_request.head.repo.full_name }} > ./commitData/repo
      - uses: actions/upload-artifact@v3
        with:
          name: commitData
          path: commitData/
