name: 'Test Docker Image with Unlighthouse'
author: 'Neshura'

on:
  push:
    tags:
      - '[0-9]+.[0-9]+.[0-9]+'
      - '[0-9]+.[0-9]+.[0-9]+-rc.[0-9]+'
  pull_request:
    branches:
      - main
jobs:
  test:
    runs-on: docker
    steps:
      - name: Checking Out Repository Code
        uses: https://code.forgejo.org/actions/checkout@v3

      - name: Get Yarn Cache Directory
        id: yarn-cache-dir-path
        run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT

      - name: Set Up Yarn Cache
        uses: actions/cache@v3
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install Dependencies
        run: yarn install

      - name: Install Chromium for Unlighthouse
        run: |
          echo "apt update && apt install -y chromium"
          apt update && apt install -y chromium
          echo 'export CHROMIUM_FLAGS="$CHROMIUM_FLAGS --no-sandbox" >> /etc/chromium.d/default-flags'
          echo 'export CHROMIUM_FLAGS="$CHROMIUM_FLAGS --no-sandbox"' >> /etc/chromium.d/default-flags

      - name: Add Unlighthouse
        run: |
          echo "yarn global add @unlighthouse/cli"
          yarn global add @unlighthouse/cli

      - name: Build Site
        run: yarn build

      - name: Start Server
        run: |
          export KUMA_USERNAME=${{ secrets.KUMA_USERNAME }}
          export KUMA_PASSWORD=${{ secrets.KUMA_PASSWORD }}
          yarn preview &

      - name: Run Unlighthouse for Desktop
        run: unlighthouse-ci --build-static --desktop --outputPath reports/desktop

      - name: Refresh Server
        run: |
          if ! pgrep -f "node /usr/bin/yarn" ; then
            export KUMA_USERNAME=${{ secrets.KUMA_USERNAME }}
            export KUMA_PASSWORD=${{ secrets.KUMA_PASSWORD }}
            yarn preview &
          fi

      - name: Run Unlighthouse for Mobile
        run: unlighthouse-ci --build-static --mobile --outputPath reports/mobile

      - name: Uploading Lighthouse Reports
        uses: actions/upload-artifact@v3
        with:
          name: lighthouse
          path: reports
          if-no-files-found: error