name: Update GitHub Pages Downloads

on:
  push:
    tags:
      - "v*"

jobs:
  update-pages:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout CrossDesk repo
        uses: actions/checkout@v4

      - name: Set version number
        id: version
        run: |
          VERSION_NUM="${GITHUB_REF##*/}"
          VERSION_NUM="${VERSION_NUM#v}"
          echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_ENV
          echo "VERSION_NUM=${VERSION_NUM}" >> $GITHUB_OUTPUT

      - name: Checkout Pages repo
        uses: actions/checkout@v4
        with:
          repository: kunkundi/kunkundi.github.io
          token: ${{ secrets.GH_PAGES_PAT }}
          path: pages

      - name: Update download links
        run: |
          cd pages
          sed -E -i "s/crossdesk-win-x64-[0-9]+\.[0-9]+\.[0-9]+\.exe/crossdesk-win-x64-${VERSION_NUM}.exe/g" index.html
          sed -E -i "s/crossdesk-macos-x64-[0-9]+\.[0-9]+\.[0-9]+\.pkg/crossdesk-macos-x64-${VERSION_NUM}.pkg/g" index.html
          sed -E -i "s/crossdesk-macos-arm64-[0-9]+\.[0-9]+\.[0-9]+\.pkg/crossdesk-macos-arm64-${VERSION_NUM}.pkg/g" index.html
          sed -E -i "s/crossdesk-linux-amd64-[0-9]+\.[0-9]+\.[0-9]+\.deb/crossdesk-linux-amd64-${VERSION_NUM}.deb/g" index.html
          sed -E -i "s/crossdesk-linux-arm64-[0-9]+\.[0-9]+\.[0-9]+\.deb/crossdesk-linux-arm64-${VERSION_NUM}.deb/g" index.html

      - name: Commit & Push changes
        run: |
          cd pages
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add index.html
          git commit -m "Update download links to v${VERSION_NUM}" || echo "No changes to commit"
          git push origin main
        env:
          VERSION_NUM: ${{ env.VERSION_NUM }}
