on: 
  pull_request:
    types: [ assigned, opened, synchronize, reopened ]

jobs:
  preview:
    runs-on: x86_64
    container:
      image: alpine:latest
    steps:
      - name: Environment setup
        run: |
          apk add git ikiwiki po4a perl-yaml-tiny tree nodejs jq coreutils curl imagemagick-perlmagick imagemagick imagemagick-jpeg findutils bash imagemagick-webp
          echo "GITHUB_PR_NAME=$(curl -Ls ${{ github.server_url }}/api/v1/repos/${{ github.repository }}/pulls/${{ github.ref_name }} -H 'accept: application/json' -H 'Authorization: token ${{ secrets.FORGEJO_TOKEN }}' | jq .title | tr ' ' '-' | tr -d ':' | tr -d '"' | tr '[:upper:]' '[:lower:]' | tr '/' '-' | tr -d ',')" >> $GITHUB_ENV
      - name: Repo pull
        uses: actions/checkout@v4
        with:
          fetch-depth: 1
      - name: Public repo pull
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: pages
          path: public
      - name: Render website
        run: |
          rm -rf public/previews/$GITHUB_PR_NAME || true
          mkdir -p public/previews/$GITHUB_PR_NAME
          sed -i "s|destdir.*|destdir: ./public/previews/$GITHUB_PR_NAME|" ikiwiki.setup
          ikiwiki --setup ikiwiki.setup
          cd public/previews
          tree -d -H '.' -L 1 --noreport --charset utf-8 -T "Versions" -o index.html
          cd $GITHUB_PR_NAME
          find -name 'index.html' -type 'l' -delete
          find -name 'index.fr.html' -exec bash -c 'ln -s "${0/.*\/}" "${0/.fr/}"' {} \;
      - name: Website upload
        run: |
          git log -1 --pretty=%B > commit.txt
          cd public
          date > previews/$GITHUB_PR_NAME/generated.txt
          echo ${{ github.sha }} > previews/$GITHUB_PR_NAME/git_sha.txt
          # Note: the following account information will not work on GHES
          git config user.name "forgejo-actions[bot]"
          git config user.email "dev@ayakael.net"
          git add .
          git commit -F ../commit.txt
          git push
