name: Trigger Repos

on:
  workflow_dispatch:
  push:
    branches: master
  release:
    types:
      - created

jobs:
  trigger-mynewt:
    if: github.repository == 'hathach/tinyusb'
    runs-on: ubuntu-latest
    steps:
    - name: Trigger mynewt-tinyusb-example
      shell: bash
      run: |
        curl -X POST -H "Authorization: token ${{ secrets.API_TOKEN_GITHUB }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches

  mirror-tinyusb-src:
    if: github.repository == 'hathach/tinyusb'
    runs-on: ubuntu-latest
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Push to tinyusb_src
      run: |
        # clone tinyusb_src with PAT
        git config --global user.email "thach@tinyusb.org"
        git config --global user.name "hathach"
        git clone --depth 1 --single-branch --branch main "https://${{ secrets.API_TOKEN_GITHUB }}@github.com/hathach/tinyusb_src.git" tinyusb_src

        # Remove all files
        rm -rf tinyusb_src/*

        # Copy src and other files
        cp -r src tinyusb_src/
        cp LICENSE tinyusb_src/
        cd tinyusb_src

        # Commit if there is changes
        if [ -n "$(git status --porcelain)" ]; then
          git add .
          git commit --message "Update from https://github.com/$GITHUB_REPOSITORY/commit/$GITHUB_SHA"
          git push
        fi

    - name: Create tinyusb_src Release
      if: ${{ github.event_name == 'release' }}
      run: |
        # Push tag
        cd tinyusb_src
        git tag ${{ github.event.release.tag_name }}
        git push origin ${{ github.event.release.tag_name }}

        # Send POST reqwuest to release https://docs.github.com/en/rest/reference/repos#create-a-release
        bb="For release note, please checkout https://github.com/hathach/tinyusb/releases/tag/${{ github.event.release.tag_name }}"
        curl -X POST -H "Authorization: token ${{ secrets.API_TOKEN_GITHUB }}" -H "Accept: application/vnd.github.v3+json" --data '{"tag_name": "${{ github.event.release.tag_name }}", "name": "${{ github.event.release.name }}", "body": "$bb", "draft": ${{ github.event.release.draft }}, "prerelease": ${{ github.event.release.prerelease }}}' https://api.github.com/repos/hathach/tinyusb_src/releases
