name: "Release"
on: 
   push:
       tags:       
         - '*'

permissions:
  contents: write

jobs:
  convert_via_pandoc:
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout repository and submodules
        uses: actions/checkout@v4
        with:
            submodules: recursive
            
      - name: Check if release exists
        id: check_release
        run: |
          if gh release view ${{ github.ref_name }} > /dev/null 2>&1; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Release for tag ${{ github.ref_name }} already exists - will update it"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
            echo "Release for tag ${{ github.ref_name }} does not exist - will create it"
          fi
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
            
      - name: Install LaTeX dependencies
        run: |
          sudo add-apt-repository -y ppa:sunderme/texstudio
          sudo apt install texlive-latex-extra bookletimposer
          
      - name: Debug - Show current directory
        run: |
          echo $PWD
          ls -al ./
          ls -al ../
          
      - name: Replace version in LaTeX file
        run: sed -i 's/VERSIONNUMBER/${{ github.ref_name }}/g' ScopeSequencing.tex
        
      - name: Generate PDF
        run: pdflatex -jobname=HowToBuildACommons-${{ github.ref_name }} ScopeSequencing.tex
        
      - name: Generate Booklet PDF
        run: bookletimposer -b -a -f "Letter" -p "2x1"  -o  HowToBuildACommons-${{ github.ref_name }}-booklet.pdf HowToBuildACommons-${{ github.ref_name }}.pdf      
        
      - name: Debug - Show generated files
        run: ls -al .
        
      - name: Create or Update Release
        uses: softprops/action-gh-release@v1
        with:
          files: HowToBuildACommons-${{ github.ref_name }}.pdf,HowToBuildACommons-${{ github.ref_name }}-booklet.pdf,how-to-consensus-zine.svg
          draft: false
          prerelease: false
          name: ${{ github.ref_name }}
          # This action automatically handles existing releases by updating them
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
