name: Create Daily Release

on:
  schedule:
    - cron: '1 0 * * *'  # Runs daily at 00:01 UTC
  workflow_dispatch:
  
jobs:
  create-daily-release:
    if: github.repository == 'community-scripts/ProxmoxVE'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Clean CHANGELOG (remove HTML header)
        run: sed -n '/^## /,$p' CHANGELOG.md > changelog_cleaned.md

      - name: Extract relevant changelog section
        run: |
          YESTERDAY=$(date -u --date="yesterday" +%Y-%m-%d)
          echo "Checking for changes on: $YESTERDAY"

          # Extract the section from "## $YESTERDAY" until the next "## YYYY-MM-DD"
          sed -n "/^## $YESTERDAY/,/^## [0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}/p" changelog_cleaned.md | head -n -1 > changelog_tmp_full.md

          # Truncate the extracted section to 5000 characters
          head -c 5000 changelog_tmp_full.md > changelog_tmp.md

          echo "=== Extracted Changelog ==="
          cat changelog_tmp.md
          echo "==========================="

          # Abort if no content was found
          if [ ! -s changelog_tmp.md ]; then
            echo "No changes found for $YESTERDAY, skipping release."
            exit 0
          fi

      - name: Create GitHub release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          YESTERDAY=$(date -u --date="yesterday" +%Y-%m-%d)
          gh release create "$YESTERDAY" -t "$YESTERDAY" -F changelog_tmp.md
