name: 'publish'

on:
    workflow_dispatch:
        inputs:
            release_type:
                description: 'release type: minor | patch | beta'
                required: true

jobs:
    publish-new-version:
        name: 'publish a new version'
        runs-on: ubuntu-latest
        steps:
            - name: gen token
              run: |
                  git config --global user.name 'semi-team'
                  git config --global user.email 'semi-team@bytedance.com'
                  mkdir ~/.ssh
                  echo $SEMI_TEAM_PRIVATE_KEY > ~/.ssh/ssh-ed25519
                  echo $SEMI_TEAM_PRIVATE_KEY_PUB > ~/.ssh/ssh-ed25519.pub
                  echo "Host\n  github.com\n  AddKeysToAgent yes\n  UseKeychain yes\n  IdentityFile ~/.ssh/id_ed25519" > ~/.ssh/config

            - uses: actions/checkout@v4

            - name: Use Node.js 20
              uses: actions/setup-node@v4
              with:
                  node-version: 20

            - name: npm install
              run: npm i -g lerna@^4.0.0 && npm run bootstrap

            - name: get version list
              run: |
                  PKG_NAME=@douyinfe/semi-ui
                  echo "VERSION_LIST="$(npm view $PKG_NAME versions --json)"" >> $GITHUB_ENV

            - name: get version
              run: echo "RELEASE_VERSION="$(node scripts/version.js)"" >> $GITHUB_ENV
              env:
                  RELEASE_TYPE: ${{ github.event.inputs.release_type }}

            - name: publish
              run: |
                  git config --global user.name 'semi-team'
                  git config --global user.email 'semi-team@bytedance.com'
                  node scripts/sitemap_update.js
                  if [ -n "$(git status --porcelain)" ]; then
                    echo "there are changes";
                    git add .
                    git commit --no-verify -m "chore: publish ${{ env.RELEASE_VERSION }}"
                  else
                    echo "no changes";
                  fi
                  npm config set registry=https://registry.npmjs.org/
                  npm config set //registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}
                  npm whoami
                  DIST_TAG=latest
                  if [[ ${{ github.event.inputs.release_type }} == 'beta' ]]; then
                    DIST_TAG=beta
                  fi
                  echo "$RELEASE_VERSION"
                  echo "$DIST_TAG"
                  lerna version $RELEASE_VERSION --exact --force-publish --yes --no-push
                  lerna publish from-package --dist-tag $DIST_TAG --yes
                  git push -o ci.skip --follow-tags --no-verify --atomic
              # env: 
                # NODE_OPTIONS: '--no-experimental-fetch --openssl-legacy-provider'
