name: Auto Update .app-headers

on:
  push:
    branches:
      - main
    paths:
      - 'ct/**.sh'
  workflow_dispatch:  # Ermöglicht das manuelle Ausführen der Action

jobs:
  update-app-headers:
    runs-on: ubuntu-latest

    permissions:
      contents: write
      pull-requests: write

    steps:
      # Step 1: Checkout repository
      - name: Checkout repository
        uses: actions/checkout@v2

      # Step 2: Set up Git user for committing changes
      - name: Set up Git
        run: |
          git config --global user.name "GitHub Actions"
          git config --global user.email "actions@github.com"

      # Step 3: Install figlet
      - name: Install figlet
        run: sudo apt-get install -y figlet

      # Step 4: Run the generate-app-headers.sh script to update .app-headers
      - name: Run generate-app-headers.sh to update .app-headers
        run: |
          chmod +x .github/workflows/scripts/generate-app-headers.sh
          .github/workflows/scripts/generate-app-headers.sh
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      # Step 5: Check if there are any changes
      - name: Check if there are any changes
        id: verify-diff
        run: |
          git diff --quiet . || echo "changed=true" >> $GITHUB_OUTPUT

      # Step 6: Commit changes (if any) and create a PR
      - name: Commit and create PR if changes exist
        if: steps.verify-diff.outputs.changed == 'true'
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git add ./misc/.app-headers
          git commit -m "Update .app-headers file"
          # Create a temporary branch for the PR
          git checkout -b pr-update-app-headers
          git push origin pr-update-app-headers --force
          
          # Create PR against main
          gh pr create --title "[core] update .app-headers file" \
                       --body "This PR is auto-generated by a Github Action to update the .app-headers file." \
                       --head pr-update-app-headers \
                       --base main \
                       --label "automated pr"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Re-approve pull request after update
        if: steps.verify-diff.outputs.changed == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR_NUMBER=$(gh pr list --head "pr-update-app-headers" --json number --jq '.[].number')
          # Check if the PR was created by the bot (skip review if so)
          PR_AUTHOR=$(gh pr view "$PR_NUMBER" --json author --jq '.author.login')
          if [ "$PR_AUTHOR" != "github-actions[bot]" ]; then
            gh pr review "$PR_NUMBER" --approve
          else
            echo "PR was created by the bot, skipping review."
          fi