name: LinUtil Preview

on:
  workflow_dispatch:
    inputs:
        tag_name:
          description: 'Tag name'
          required: true
  workflow_run:
    workflows: ["LinUtil Release"]
    types:
      - completed

jobs:
  generate_preview:
    runs-on: ubuntu-latest
    environment: linutil_env
    permissions:
      contents: write
      pull-requests: write

    steps:
      - name: Checkout source
        uses: actions/checkout@v4

      - name: Get tag name ( Workflow Run )
        id: latest_tag
        uses: actions/github-script@v7
        if: github.event_name == 'workflow_run'
        with:
          script: |
            const releases = await github.rest.repos.listReleases({
              owner: context.repo.owner,
              repo: context.repo.repo,
              per_page: 1
            });
            return releases.data[0].tag_name;

      - name: Set tag name ( Workflow Run )
        if: github.event_name == 'workflow_run'
        run: echo "tag_name=${{ steps.latest_tag.outputs.result }}" >> $GITHUB_ENV

      - name: Set tag name ( Workflow Dispatch )
        if: github.event_name == 'workflow_dispatch'
        run: echo "tag_name=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV

      - name: Download binary
        run: |
          curl -LO "https://github.com/${{ github.repository }}/releases/download/${{ env.tag_name }}/linutil"
        
      - name: Install ffmpeg
        run: sudo apt-get update && sudo apt-get install -y ffmpeg

      - name: Set env
        run: |
          chmod +x linutil
          mkdir -p build
          mv linutil build/linutil
          echo "${{ github.workspace }}/build" >> $GITHUB_PATH
          echo "branch_name=${{ env.tag_name }}" | tr . - >> $GITHUB_ENV

      - name: Generate preview
        uses: charmbracelet/vhs-action@v2.1.0
        with:
          path: ".github/preview.tape"

      - name: Move preview
        run: mv preview.gif .github/preview.gif

      - name: Create PR
        uses: peter-evans/create-pull-request@v7.0.5
        with:
          commit-message: Preview for ${{ env.tag_name }}
          branch: preview-${{ env.branch_name }}
          title: "Update preview for ${{ env.tag_name }}"
          labels: |
            documentation
          body: |
            Automated PR to update preview gif for version ${{ env.tag_name }}
            ![preview](https://raw.githubusercontent.com/${{ github.repository }}/preview-${{ env.branch_name }}/.github/preview.gif)
        if: success()
