name: Initialize

on:
  push:
    branches:
      - main

jobs:
  initialize:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: step-security/harden-runner@v2
        with:
          egress-policy: audit
      - uses: actions/checkout@v6
        with:
          token: ${{ secrets.GH_TOKEN }}
      - uses: actions/setup-node@v6
        with:
          node-version: 21
      - run: git pull

      - name: Run replace-all-words
        run: npx replace-all-words ./ 'template-typescript-npm-cli' "${{ github.event.repository.name }}"
        if: ${{ github.event.repository.name }} != 'template-typescript-npm-cli'
      - uses: stefanzweifel/git-auto-commit-action@v7
        with:
          commit_message: 'autogen: replace template with repository name and remove initialize / npx replace-all-words ./ template-typescript-npm-cli ${{ github.repository }}'

      - name: Remove job for initialize
        run: rm .github/workflows/initialize.yml
        if: ${{ !startsWith(github.event.repository.name, 'template-') }}
      - uses: stefanzweifel/git-auto-commit-action@v7
        with:
          commit_message: 'autogen: remove job for initialize / rm .github/workflows/initialize.yml'

      - name: Trigger repository-management
        if: ${{ !contains(github.event.repository.name, 'template') }}
        run: |
          curl -X POST -f -H "Authorization: token ${{ secrets.GH_TOKEN }}" \
               -H "Accept: application/vnd.github.v3+json" \
               "https://api.github.com/repos/HiromiShikata/repositories-management/actions/workflows/repositories-management.yml/dispatches" \
               -d '{
                 "ref": "main",
                 "inputs": {
                 }
               }'
