name: Deploy to gh-pages branch

on:
  push:
    branches:
      - main
    paths:
      - 'EasyDutch/**'
      - 'EasyDutch.txt'

# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-only-cancel-in-progress-jobs-or-runs-for-the-current-workflow
concurrency: 
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  publish:
    permissions:
      contents: write  # for Git to git push
    name: Publish lists
    runs-on: ubuntu-latest
    steps:
      - name: Repo check
        run: |
          if [[ "$GITHUB_REPOSITORY_OWNER" != "EasyDutch-uBlockOrigin" ]]; then
            echo "This GitHub Action is meant to deliver filter lists for EasyDutch."
            echo "You shouldn't need to run this GitHub Action in your fork."
            exit 1
          fi
          exit 0
      - name: Sleep for 5 minutes
        run: sleep 300s
        shell: bash
      - name: Clone EasyDutch
        uses: actions/checkout@v6
        with:
          ref: gh-pages
      - name: Generate version string
        run: |
          TAGNAME=$(date -u "+%Y.%-m.%-d.")$(date -u "+%H*60+%M" | bc)
          echo "TAGNAME=$TAGNAME" >> $GITHUB_ENV
          echo "Version string is $TAGNAME"
      - name: Copy filter lists to gh-pages
        run: |
          TMPFILE="$(mktemp -d)"
          echo "TMPFILE=$TMPFILE" >> "$GITHUB_ENV"
          git clone --depth=1 https://github.com/EasyDutch-uBlockOrigin/EasyDutch.git "$TMPFILE"
          pushd "$TMPFILE" > /dev/null
          echo "*** EasyDutch: Assembling EasyDutch.txt"
          node ./tools/make-easydutch.mjs in=./tools/easydutch-filters.template out=./EasyDutch.all.txt minify=1
          popd > /dev/null
          cp "$TMPFILE"/EasyDutch/*.txt EasyDutch/
          cp "$TMPFILE"/EasyDutch.txt EasyDutch.txt
          cp "$TMPFILE"/EasyDutch.all.txt EasyDutch.all.txt
      - name: Patch last-updated field
        run: |
          DATE=$(date -Ru)
          for f in $(git diff --name-only); do
            STAT=$(git diff --numstat $f | sed -r '/^1\s+1\s+/d')
            if [[ -n $STAT ]]; then
              sed -ir "0,/^! Last updated: /s/^\(! Last updated: \)%timestamp%/\\1$DATE/" $f
            else
              git checkout -q $f
            fi
          done
      - name: Create new patch
        run: |
          chmod 755 "$TMPFILE"/tools/make-diffpatch.sh
          PATCHES_DIR="patches"
          "$TMPFILE"/tools/make-diffpatch.sh "${{ env.TAGNAME }}" "$PATCHES_DIR"
      - name: Update existing patch
        run: |
          chmod 755 "$TMPFILE"/tools/update-diffpatches.sh
          PATCHES_DIR="patches"
          FILTER_FILES=$(git ls-files --exclude-standard -- EasyDutch.all.txt)
          "$TMPFILE"/tools/update-diffpatches.sh "$GITHUB_REPOSITORY" "$PATCHES_DIR" "$FILTER_FILES"
      - name: Commit changes (if any)
        run: |
          if [[ -z $(git diff --name-only --cached) ]]; then exit 0; fi
          git config user.name "GitHub Actions"
          git config user.email "<>"
          git commit -m "Update modified filter lists to ${{ env.TAGNAME }}"
          git push origin gh-pages
          git tag ${{ env.TAGNAME }}
          git push origin ${{ env.TAGNAME }}
      - name: Remove obsolete tags
        run: |
          git fetch --force --tags
          mapfile -t PATCHES < <(
            ls -1v patches/*.patch |
            sed 's|^.*/||; s|\.patch$||'
          )
          KEEP_TAGS=() # Keep all retained patch versions
          for tag in "${PATCHES[@]}"; do
            KEEP_TAGS+=("$tag")
          done
          KEEP_TAGS+=("$(cat version)") # Keep current version
          if [[ ${#PATCHES[@]} -gt 0 ]]; then # Keep one version older than the oldest retained patch
            OLDEST_PATCH="${PATCHES[0]}"
            PREVIOUS_TAG=$(
              git tag --sort=v:refname |
              awk -v oldest="$OLDEST_PATCH" '$0 < oldest { prev=$0 } END { print prev }'
            )
            if [[ -n "$PREVIOUS_TAG" ]]; then
              KEEP_TAGS+=("$PREVIOUS_TAG")
            fi
          fi
          for tag in $(git tag); do
            if ! printf '%s\n' "${KEEP_TAGS[@]}" | grep -qxF "$tag"; then
              echo "Removing obsolete tag $tag"
              git tag -d "$tag"
              git push origin ":refs/tags/$tag"
            fi
          done
