name: Update README

permissions:
  contents: write

on:
  workflow_dispatch:
  schedule:
    - cron: "0 4 * * *" # Every day at 4 AM UTC

jobs:
  update-readme:
    runs-on: ubuntu-latest
    container:
      image: catthehacker/ubuntu:act-latest

    env:
      SOURCE_REPO: ivancarlos/.gitea
      SOURCE_BRANCH: main

    steps:
      - name: Checkout current repository
        uses: actions/checkout@v4

      - name: Checkout source README template
        uses: actions/checkout@v4
        with:
          repository: ${{ env.SOURCE_REPO }}
          ref: ${{ env.SOURCE_BRANCH }}
          token: ${{ secrets.CR_PAT }}
          path: source_readme

      - name: Update README.md (footer only)
        run: |
          set -e

          # --- Extract footer block from source (everything from <!-- footer --> onward) ---
          FOOTER=$(awk '/<!-- footer -->/{flag=1}flag' source_readme/README.md)

          # --- Replace everything after <!-- footer --> with FOOTER ---
          awk -v footer="$FOOTER" '
            /<!-- footer -->/ {
              print footer
              found=1
              exit
            }
            { print }
          ' README.md > README.tmp && mv README.tmp README.md

      - name: Remove source_readme from git index
        run: rm -rf source_readme

      - name: Commit and push changes
        run: |
          git config user.name "Gitea Actions"
          git config user.email "actions@git.icc.gg"
          git add README.md
          git commit -m "Sync README from template [▶️]" || echo "Nothing to commit"
          git push origin ${{ github.ref_name }}
