#!/bin/bash

files_to_copy=("package.json" ".npmignore" "yarn.lock" "../../.hygen" "../../.hygen.js")

if [ -d "dist" ]; then
    rm -rf dist
fi

yarn run build

if [ ! -d "dist" ]; then
    echo "dist directory was not created by the build command."
    exit 1
fi

# 新增测试版发布询问
read -p "是否发布测试版？(yes/no) " is_beta

# 版本号递增逻辑
if [[ "$is_beta" =~ ^[Yy](es)?$ ]]; then
    npm version prerelease -m "Bump version for beta release"
else
    npm version patch -m "Bump version for release"
fi

# 文件复制（注意调整到版本号递增之后）
for file in "${files_to_copy[@]}"; do
  if [ -f "$file" ]; then
    cp "$file" dist/
  elif [ -d "$file" ]; then
    cp -rf "$file" dist/
  else
    echo "Warning: $file does not exist and cannot be copied to dist."
  fi
done

# 发布逻辑
cd dist || exit
if [[ "$is_beta" =~ ^[Yy](es)?$ ]]; then
    npm publish --tag beta --access public
else
    npm publish --access public
fi

echo "Build completed, files copied to dist, and package published to npm."
