# 当分支 main 有 push 事件，并且此次 push 包含了 demo 目录下的文件时触发，使用 GitHub Actions 执行

name: SYNC DEMO

on:
    push:
        branches:
            - main
        paths:
            - 'demo/**'

jobs:
    build-and-deploy:
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v2

            # clone 仓库 github.com/dufu1991/stdf
            - name: Clone stdf
              uses: actions/checkout@v3
              with:
                  repository: dufu1991/stdf
                  token: ${{ secrets.STDF_GITHUB_TOKEN }}
                  path: stdf

            # 读取 packages/stdf/package.json 中的 version 字段，作为 stdf 的最新版本
            - name: Get version
              id: version
              run: |
                  echo version=$(cat packages/stdf/package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[[:space:]]') >> $GITHUB_OUTPUT

            # 读取 packages/rollup-plugin-stdf-icon/package.json 中的 version 字段，作为 rollup-plugin-stdf-icon 的最新版本
            - name: Get rollup-plugin-stdf-icon version
              id: rollup-plugin-stdf-icon-version
              run: |
                  echo rollup-plugin-stdf-icon-version=$(cat packages/rollup-plugin-stdf-icon/package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[[:space:]]') >> $GITHUB_OUTPUT

            # cd 到 stdf/demo 文件内，初始化本地仓库
            # 将 demo/package.json 内的 file:../packages/stdf 替换为 ^${{ steps.version.outputs.version }}
            # 将 demo/package.json 内的 file:../packages/rollup-plugin-stdf-icon 替换为 ^${{ steps.rollup-plugin-stdf-icon-version.outputs.rollup-plugin-stdf-icon-version }}
            # 将 demo 目录下的所有文件提交到本地仓库，提交信息为 Github Actions auto commit: update demo from stdf.
            - name: Init stdf demo
              run: |
                  cd stdf/demo
                  git init
                  git config --global user.name 'GitHub Actions'
                  git config --global user.email 'GitHub Actions'
                  sed -i 's#file:../packages/stdf#^${{ steps.version.outputs.version }}#' package.json
                  sed -i 's#file:../packages/rollup-plugin-stdf-icon#^${{ steps.rollup-plugin-stdf-icon-version.outputs.rollup-plugin-stdf-icon-version }}#' package.json
                  git add .
                  git commit -m "Github Actions auto commit: update demo from stdf."

            # 将修改内容推送到 git@github.com:dufu1991/demo-stdf.git 的 main 分支
            - name: Push to demo-stdf
              uses: ad-m/github-push-action@master
              with:
                  github_token: ${{ secrets.STDF_GITHUB_TOKEN }}
                  branch: main
                  force: true
                  directory: stdf/demo
                  repository: dufu1991/demo-stdf
