name: assets1
on:
  push:
    branches:
      - main
jobs:
  test:
    if: ${{ github.actor != 'ui-asset-bot' }}
    runs-on: nix
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Get changed files using defaults
        id: changed-files
        uses: tj-actions/changed-files@v32
        with:
          fetch-depth: 0

      - name: Check if UI files are in the list of modified files
        run: |
          set -xeuo pipefail
          echo "Modified files: $MODIFIED_FILES"
          if echo "$MODIFIED_FILES" | grep -q "pkgs/ui/" \
          || echo "$MODIFIED_FILES" | grep -q ".gitea/workflows/ui_assets.yaml"; then

            echo "UI files have changed"
            bash ./pkgs/ui/nix/update-ui-assets.sh


            # git push if we have a diff
            if [[ -n $(git diff) ]]; then

              DEPS=$(nix shell --inputs-from '.#' "nixpkgs#coreutils-full" -c bash -c "echo \$PATH")
              export PATH=$PATH:$DEPS

              # Setup git config
              git config --global user.email "$BOT_EMAIL"
              git config --global user.name "$BOT_NAME"

              ################################################
              #                                              #
              # WARNING: SECRETS ARE BEING PROCESSED HERE.   #
              #             !DO NOT LOG THIS!                #
              #                                              #
              ################################################
              set +x
              AUTH_TOKEN=$(echo -n "x-access-token:$GITEA_TOKEN" | base64)
              git config http."$GITHUB_SERVER_URL/".extraheader "AUTHORIZATION: basic $AUTH_TOKEN"
              set -x
              ################################################
              #                                              #
              #             END OF SECRETS AREA              #
              #                                              #
              ################################################

              # Commit and push
              git commit -am "update ui-assets.nix"

              echo "Current branch: $GITHUB_REF_NAME"
              git push origin HEAD:"$GITHUB_REF_NAME"
              echo "Done uploading"
            fi
          else
            echo "No UI files changed. Skipping asset build and push"
          fi
        env:
          MODIFIED_FILES: ${{ steps.changed-files.outputs.modified_files }}
          GITEA_TOKEN: ${{ secrets.BOT_ACCESS_TOKEN }}
          BOT_NAME: "ui-asset-bot"
          BOT_EMAIL: "ui-asset-bot@gchq.icu"
