name: "Generate Patches"
on:
  push:
    branches:
      - main

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: "Checkout"
        uses: actions/checkout@v3
        
      - name: "Check for [NOBUILD] in commit message"
        id: nobuild_check
        run: |
          if [[ "${{ github.event.head_commit.message }}" == *"[NOBUILD]"* ]]; then
            echo "NOBUILD flag detected, stopping workflow."
            exit 1
          fi
          
      - name: "Setup Python"
        uses: actions/setup-python@v5.1.1
        with:
          python-version: 3.12.0
          architecture: x64
      
      - run: python3 Scripts/pchtxt2ips.py batch Patches Out

      - name: "Create dynamic tag name"
        id: create_tag
        run: |
          # Generate a tag name based on the date and short commit hash
          TAG_NAME="v$(date +'%Y%m%d')-$(git rev-parse --short HEAD)"
          echo "TAG_NAME=$TAG_NAME" >> $GITHUB_ENV


      - name: "Create zip of IPS files"
        run: |
          mkdir -p tmp/atmosphere/exefs_patches/fortpatcher
          cp Out/*.ips tmp/atmosphere/exefs_patches/fortpatcher/
          cd tmp && zip -r ../Out/all_patches.zip atmosphere


      - name: "Create GitHub release"
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{github.token}}
        with:
          tag_name: ${{ env.TAG_NAME }}
          release_name: Release ${{ env.TAG_NAME }}
          draft: false
          prerelease: false

      - name: "Upload individual IPS files to release"
        env:
          GITHUB_TOKEN: ${{github.token}}
        run: |
          for file in Out/*.ips; do
            gh release upload ${{ env.TAG_NAME }} "$file" --clobber
          done

      - name: "Upload zip file to release"
        run: gh release upload ${{ env.TAG_NAME }} Out/all_patches.zip --clobber
        env:
          GITHUB_TOKEN: ${{github.token}}