#  MIT License
#
#  Copyright (c) 2022 anatawa12
#  Copyright (c) 2022 bd_
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#  SOFTWARE.


name: GameCI

on:
  push:
    branches: [main, dev, ci, refactor-structure]
  # This is a bit of a radioactive event; we need to be very careful with what permissions
  # we assign this action, as we're allowing arbitrary code execution with the context of
  # whatever permissions we assign.
  pull_request_target: {}
  workflow_dispatch: {}
  workflow_call:
    secrets:
      UNITY_LICENSE:
        required: true

# pull_request_target grants access to a privileged GITHUB_TOKEN by default, revoke this
permissions: {}

jobs:
  build-and-test:
    name: Unit tests
    strategy:
      matrix:
        unity_major_version: [ 2019, 2022 ]
        sdk: [ vrcsdk ]
    runs-on: ubuntu-latest
    permissions:
      checks: write
      contents: read
    steps:
      - id: configure
        name: Configure
        env:
          unity_major_version: ${{ matrix.unity_major_version }}
        run: |
          if [ $unity_major_version == 2019 ]; then
            echo "unity_version=2019.4.31f1" >> $GITHUB_OUTPUT
          elif [ $unity_major_version == 2022 ]; then
            echo "unity_version=2022.3.6f1" >> $GITHUB_OUTPUT
          else
            echo "Invalid unity_major_version: $unity_major_version"
            exit 1
          fi 
      - id: setup
        name: Setup
        env:
          unity_version: ${{ steps.configure.outputs.unity_version }}
          sdk: ${{ matrix.sdk }}
        run: |
          set -x
          
          sudo apt-get install xmlstarlet -y
          
          should_test=true
          echo should_test=$should_test >> $GITHUB_OUTPUT
          
          can_fail=false
          if [ $sdk == standalone ]; then
            can_fail=$should_test
          fi
          echo can_fail=$can_fail >> $GITHUB_OUTPUT
          
          if $can_fail; then
            check_name="Unsupported test result ($unity_version, $sdk)"
          else
            check_name="Test result ($unity_version, $sdk)"
          fi
          echo check_name=$check_name >> $GITHUB_OUTPUT

      - uses: actions/checkout@v4
        if: ${{ steps.setup.outputs.should_test == 'true' }}
        with:
          ref: ${{ github.event.pull_request.head.sha }}

      - id: prepare-project
        if: ${{ steps.setup.outputs.should_test == 'true' }}
        name: Prepare project
        run: |
          mkdir .github/ProjectRoot/Packages/nadena.dev.modular-avatar -p
          mv * .github/ProjectRoot/Packages/nadena.dev.modular-avatar
          mv .github/ProjectRoot/* .
          mv 'Packages/nadena.dev.modular-avatar/UnitTests~' 'Packages/nadena.dev.modular-avatar/UnitTests'
          for i in packages-lock manifest vpm-manifest; do
            if [ -e "$i-${{ matrix.unity_major_version }}.json" ]; then
              mv "$i-${{ matrix.unity_major_version }}.json" Packages/$i.json -v
            fi
          done

      - uses: anatawa12/sh-actions/resolve-vpm-packages@master
        name: Resolve VPM packages
        if: ${{ matrix.sdk == 'vrcsdk' && steps.setup.outputs.should_test == 'true' }}
        with:
          repos: |
            https://vpm.nadena.dev/vpm-prerelease.json

      - if: ${{ steps.setup.outputs.should_test == 'true' }}
        name: "Debug: List project contents"
        run: |
          ls -lR
          ls -lR Packages/nadena*
          
      - if: ${{ steps.setup.outputs.should_test == 'true' }}
        name: "Debug: List package versions"
        run: |
          for i in Packages/*/package.json; do
            echo $i
            cat $i | jq .version
          done

      - uses: actions/cache@v4
        if: ${{ steps.setup.outputs.should_test == 'true' }}
        with:
          path: Library
          key: Library-${{ steps.configure.outputs.unity_version }}-${{ matrix.sdk }}
          restore-keys: Library-

      - uses: game-ci/unity-test-runner@v3
        id: gameci
        continue-on-error: ${{ steps.setup.outputs.can_fail == 'true' }}
        if: ${{ steps.setup.outputs.should_test == 'true' }}
        env:
          # meh, just a personal license...
          UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }}
        with:
          testMode: EditMode
          unityVersion: ${{ steps.configure.outputs.unity_version }}
          githubToken: ${{ github.token }}
          coverageOptions: generateAdditionalMetrics;generateHtmlReport;generateBadgeReport;assemblyFilters:+nadena.dev.*
          customParameters: -nographics -assemblyNames Tests
          checkName: ${{ steps.setup.outputs.check_name }}

      # For our main "supported" platforms, we report the conclusion of gameci as-is. However, for standalone, we report
      # neutral if it failed.
      - id: determine_conclusion
        name: Determine conclusion
        if: ${{ steps.setup.outputs.should_test == 'true' }}
        env:
          unity_version: ${{ steps.configure.outputs.unity_version }}
          sdk_platform: ${{ matrix.sdk }}
          gameci_outcome: ${{ steps.gameci.outcome }}
          can_fail: ${{ steps.setup.outputs.can_fail }}
        run: |
          set -x
          outcome=$gameci_outcome          
          
          # Check whether any tests actually ran
          test_count=$(
              if ! cat ${{ steps.gameci.outputs.artifactsPath }}/editmode-results.xml | \
                    xmlstarlet sel -t -v "/test-run/@total"; then
                echo 0
              fi
          )
          
          if [ $test_count -eq 0 ] || [ x$test_count == x ]; then
            outcome=failure
            output="{ \"summary\": \"No tests ran\" }"
          
            if ! $can_fail; then
              exit 1
            fi
          else
            output="{ \"summary\": \"Result: $outcome ($test_count tests)\" }"
          fi
          
          if [ "$outcome" == "failure" ] && $can_fail; then
            outcome=neutral
          fi
          echo matrix_outcome=$outcome >> $GITHUB_OUTPUT
          echo matrix_output=$output >> $GITHUB_OUTPUT

      - uses: actions/upload-artifact@v4
        if: ${{ steps.setup.outputs.should_test == 'true' && matrix.sdk == 'vrcsdk' }}
        continue-on-error: true
        with:
          name: Coverage results ${{ steps.configure.outputs.unity_version }} ${{ matrix.sdk }}
          path: ${{ steps.gameci.outputs.coveragePath }}