name: Update Site Version Number

on:
  workflow_dispatch:
  release:
    types: [published]

permissions: {}

jobs:
  build:
    name: 'Update Site Version Number'
    runs-on: ubuntu-latest

    permissions:
      contents: read

    steps:
    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd #v6.0.2
      with:
        repository: FreeTubeApp/FreeTubeApp.io
        token: ${{ secrets.FLATHUB_TOKEN }}
        persist-credentials: true

    - name: Get releases
      id: releases
      shell: bash
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      # Fetch 4 releases as filtering out drafts happens on the client side and we are unlikely to have more than 2 drafts open at the same time
      run: |
        tags="$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-drafts --json tagName --limit 4)"

        {
          echo 'versions<<EOF'
          echo "$tags" | jq --compact-output 'map(.tagName | ltrimstr("v") | rtrimstr("-beta"))'
          echo EOF
        } >> "$GITHUB_OUTPUT"

    - name: Set Master Branch
    # Currently the default branch is master, but if that changes later, then this acts as a failsafe.
      shell: bash
      run: |
        git checkout master

    - name: Update index.php
      shell: bash
      env:
        CURRENT: ${{ fromJson(steps.releases.outputs.versions)[0] }}
        PREVIOUS: ${{ fromJson(steps.releases.outputs.versions)[1] }}
      run: |
        sed -i "s/${PREVIOUS}/${CURRENT}/g" src/index.php

    - name: Commit and push
      shell: bash
      env:
        CURRENT: ${{ fromJson(steps.releases.outputs.versions)[0] }}
      run: |
        git fetch --depth=1
        git add src/index.php
        git -c user.name='github-actions[bot]' \
            -c user.email='41898282+github-actions[bot]@users.noreply.github.com' \
            commit -m "Update version number to v$CURRENT" \
            --no-verify --signoff
        git push --set-upstream origin master
