#!/bin/bash

# 设置插件目录
pluginDir=~/Library/Containers/com.kingsoft.wpsoffice.mac/Data/.kingsoft/wps/jsaddons/

# 设置压缩包URL地址
pluginUrl="https://16win.cn/wps/markdown2text/markdown2doc_1.0.0.zip"

# 插件目录和文件夹名称
pluginFolder="markdown2doc_1.0.0"
zipFile="plugin.zip"

# 下载插件压缩包
echo "下载插件压缩包..."
curl -o $pluginDir/$zipFile $pluginUrl

# 解压缩压缩包
echo "解压插件..."
unzip -q $pluginDir/$zipFile -d $pluginDir

# 删除压缩包文件
rm $pluginDir/$zipFile

# 创建或修改 jsplugins.xml
jspluginsFile="$pluginDir/jsplugins.xml"
pluginContent='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jsplugins>
    <jsplugin name="markdown2doc" type="wps" url="https://16win.cn/wps/markdown2text/dist/" version="1.0.0" />
</jsplugins>'

# 检查 jsplugins.xml 是否存在
if [ -f "$jspluginsFile" ]; then
    # 如果文件已存在，追加插件信息
    echo "修改现有的 jsplugins.xml 文件..."
    sed -i "" '/<\/jsplugins>/i\
    <jsplugin name="markdown2doc" type="wps" url="https://16win.cn/wps/markdown2text/dist/" version="1.0.0" />
    ' $jspluginsFile
else
    # 如果文件不存在，创建并写入内容
    echo "创建新的 jsplugins.xml 文件..."
    echo "$pluginContent" > $jspluginsFile
fi

# 重启 WPS
echo "重启 WPS..."
killall wps wpsoffice wpscloudsvr wpsclouds 2>/dev/null

# 延迟几秒钟以确保 WPS 关闭
sleep 5

# 启动 WPS
open -a "wpsoffice"

echo "插件安装完成！"