name: generate index

on:
  push:
    branches:
      - pages
  workflow_dispatch:

concurrency:
  group: index
  cancel-in-progress: true

jobs:
  generate:
    runs-on: codeberg-tiny
    steps:
      - name: checkout repository
        uses: actions/checkout@v5
        with:
          token: ${{ forge.token }}
          fetch-depth: 0

      - name: generate index.html
        run: |
          listing=""
          while IFS= read -r file; do
            timestamp=$(git log -1 --format=%ct -- "$file" 2>/dev/null || echo "0")
            if [ "$timestamp" -eq 0 ]; then
              mtime="1970-01-01T00:00:00Z"
            else
              mtime=$(date -u -d "@$timestamp" +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null)
              [ -z "$mtime" ] && mtime="1970-01-01T00:00:00Z"
            fi
            size=$(stat -c %s -- "$file" 2>/dev/null || stat -f %z -- "$file" 2>/dev/null || echo "0")
            if [ "$size" -lt 1024 ]; then
              size_fmt="${size}"
            else
              size_fmt=$(numfmt --to=iec --suffix=B --format="%.1f" "$size" 2>/dev/null | sed -E 's/([0-9.]+)([KMGTPE])B/\1 \2iB/')
            fi
            file_escaped=$(echo "$file" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g')
            listing="${listing}<tr><td><a href=\"/${file_escaped}\">${file_escaped}</a></td><td>${mtime}</td><td>${size_fmt}</td></tr>"$'\n'
          done < <(git ls-files)
          awk -v listing="$listing" '{ if (/{{LISTING}}/) print listing; else print }' _index.html > index.html

      - name: commit and push index.html
        run: |
          git config user.name "Codeberg Pages"
          git config user.email "pages@codeberg.org"
          timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
          git add index.html
          if ! git diff --cached --quiet; then
            git commit -m "pages: index ${timestamp}"
            git push
          else
            echo "no changes to commit"
          fi
