on:
  push:
    branches:
      - main

name: release-please

permissions:
  contents: write
  pull-requests: write

jobs:
  release-please:
    runs-on: ubuntu-latest
    outputs:
      release_created: ${{ steps.release.outputs.release_created }}
      tag_name: ${{ steps.release.outputs.tag_name }}
    steps:
      - uses: google-github-actions/release-please-action@v4
        id: release
      - uses: actions/checkout@v3
        if: ${{ steps.release.outputs.release_created }}
      - name: tag stable versions
        if: ${{ steps.release.outputs.release_created }}
        run: |
          git config user.name github-actions[bot]
          git config user.email github-actions[bot]@users.noreply.github.com
          git remote add gh-token "https://${{ secrets.GITHUB_TOKEN }}@github.com/google-github-actions/release-please-action.git"
          git tag -f -a release -m "Last Stable Release"
          git push origin release -f

  luarocks-upload:
    needs: release-please
    if: ${{ needs.release-please.outputs.release_created }}
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0 # Required to count the commits
      - name: Get Version
        run: echo "LUAROCKS_VERSION=${{ needs.release-please.outputs.tag_name }}" >> $GITHUB_ENV
      - name: LuaRocks Upload
        uses: nvim-neorocks/luarocks-tag-release@v5
        env:
          LUAROCKS_API_KEY: ${{ secrets.LUAROCKS_API_KEY }}
        with:
          version: ${{ env.LUAROCKS_VERSION }}

  update-doc:
    needs: release-please
    if: ${{ ! needs.release-please.outputs.release_created }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          ref: release-please--branches--main
          # Fetch the last 2 commits instead of just 1. (Fetching just 1 commit would overwrite the whole history)
          fetch-depth: 2

      - uses: leafo/gh-actions-lua@v10
        with:
          luaVersion: "5.1.5"

      - uses: leafo/gh-actions-luarocks@v4

      - name: Update doc
        run: make gen_help

      - name: Update PR
        run: |
          git config user.name github-actions[bot]
          git config user.email github-actions[bot]@users.noreply.github.com
          git remote add gh-token "https://${{ secrets.GITHUB_TOKEN }}@github.com/google-github-actions/release-please-action.git"
          git diff
          git add doc
          git commit --amend --no-edit
          git push --force

