name: Update mods.json

on:
  workflow_dispatch:

jobs:
  update-mods:
    runs-on: ubuntu-latest
    steps:
      - name: Install jq
        run: sudo apt-get update && sudo apt-get install -y jq

      - name: Get list of .zip files in Factorio
        env:
          GITEA_TOKEN: ${{ secrets.gamerarena }}
          GITEA_API_URL: https://git.garpnet.it/api/v1
          OWNER: GamerArena
          REPO: FastDL
          BRANCH: main
        run: |
          response=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
            "$GITEA_API_URL/repos/$OWNER/$REPO/contents/Factorio?ref=$BRANCH")
          
          zip_files=$(echo "$response" | jq -r '.[] | select(.type=="file") | select(.name|endswith(".zip")) | .name')
          json_array=$(echo "$zip_files" | jq -R -s -c 'split("\n")[:-1]')
          echo "$json_array" > mods.json
          echo "Lista file .zip: $json_array"

      - name: Get current mods.json SHA
        id: getsha
        env:
          GITEA_TOKEN: ${{ secrets.gamerarena }}
          GITEA_API_URL: https://git.garpnet.it/api/v1
          OWNER: GamerArena
          REPO: FastDL
          BRANCH: main
        run: |
          response=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
            "$GITEA_API_URL/repos/$OWNER/$REPO/contents/Factorio/mods.json?ref=$BRANCH")
          sha=$(echo "$response" | jq -r '.sha // empty')
          echo "sha=$sha" >> $GITHUB_OUTPUT

      - name: Update mods.json via API
        env:
          GITEA_TOKEN: ${{ secrets.gamerarena }}
          GITEA_API_URL: https://git.garpnet.it/api/v1
          OWNER: GamerArena
          REPO: FastDL
          BRANCH: main
          SHA: ${{ steps.getsha.outputs.sha }}
        run: |
          content=$(base64 -w 0 mods.json)
          if [ -n "$SHA" ]; then
            # Aggiorna il file esistente
            curl -X PUT -H "Authorization: token $GITEA_TOKEN" \
                 -H "Content-Type: application/json" \
                 -d "{\"content\":\"$content\",\"sha\":\"$SHA\",\"branch\":\"$BRANCH\",\"message\":\"Update mods.json\"}" \
                 "$GITEA_API_URL/repos/$OWNER/$REPO/contents/Factorio/mods.json"
          else
            # Crea il file se non esiste
            curl -X PUT -H "Authorization: token $GITEA_TOKEN" \
                 -H "Content-Type: application/json" \
                 -d "{\"content\":\"$content\",\"branch\":\"$BRANCH\",\"message\":\"Create mods.json\"}" \
                 "$GITEA_API_URL/repos/$OWNER/$REPO/contents/Factorio/mods.json"
          fi
