name: Create Release

on:
  push:
    tags:
      - 'v*'

jobs:
  build:
    name: Create Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Get the version
        id: get_version
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV

      # 获取当前版本贡献者
      - name: Fetch Contributors
        id: contributors
        run: |
          USERNAME_LIST=""

          # 获取完整的提交历史
          git fetch --prune --unshallow

          # 按日期排序标签，获取上一个标签
          PREVIOUS_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short)' refs/tags | sed -n 2p)

          # 获取当前标签
          CURRENT_TAG=${GITHUB_REF#refs/tags/}

          echo "Previous Tag: $PREVIOUS_TAG"
          echo "Current Tag: $CURRENT_TAG"

          for COMMIT_SHA in $(git log ${PREVIOUS_TAG}...$CURRENT_TAG --pretty=format:"%H")
          do
            USER=$(curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
                   https://api.github.com/repos/${GITHUB_REPOSITORY}/commits/$COMMIT_SHA \
                   | jq -r '.author.login')
            if [ "$USER" != "null" ] && [ ! -z "$USER" ]; then
              USERNAME_LIST="$USERNAME_LIST @$USER"
            fi
          done
          USERNAME_LIST=$(echo $USERNAME_LIST | tr ' ' '\n' | sort -u | tr '\n' ' ')
          echo "usernames=$USERNAME_LIST" >> $GITHUB_OUTPUT

      - name: Determine Prerelease
        id: prerelease
        run: |
          if [[ ${{ github.ref }} =~ - ]]; then
            echo "Setting prerelease to true"
            echo "prerelease=true" >> $GITHUB_OUTPUT
          else
            echo "Setting prerelease to false"
            echo "prerelease=false" >> $GITHUB_OUTPUT
          fi

      - name: Create Zip File
        id: asset
        run: |
          DIR_NAME="layui-${{ env.VERSION }}"
          mkdir -p $DIR_NAME/layui
          mv dist layui
          mv layui $DIR_NAME/
          mv examples/introduce/* $DIR_NAME/
          7z a $DIR_NAME.zip $DIR_NAME
          echo "filename=$DIR_NAME" >> $GITHUB_OUTPUT

      - name: GH Release
        id: create_release
        uses: softprops/action-gh-release@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          body: |
            - **更新日志**: https://layui.dev/docs/2/versions.html#${{ env.VERSION }}
            - **本次贡献**: ${{ steps.contributors.outputs.usernames }} 🎉
          prerelease: ${{ steps.prerelease.outputs.prerelease }}
          files: ${{ steps.asset.outputs.filename }}.zip
