#!/bin/bash
# OnlyOffice x2t 渲染 docx → PDF
# 用途：用Maggie/Doro实际使用的渲染引擎(OnlyOffice)把合同docx渲染成PDF，
#       核对编号/格式的真实显示效果（与LibreOffice/python模拟可能不同，核对一律以此为准）。
# 用法: ./onlyoffice-render.sh /path/to/合同.docx [输出PDF路径]
#   不给输出路径时，默认输出到 同目录/同名.pdf
# 依赖: OnlyOffice容器 nextcloud-onlyoffice-1 在运行；x2t在容器内
#       /var/www/onlyoffice/documentserver/server/FileConverter/bin/x2t
# 之后用: pdftotext -layout out.pdf - | grep -nE "^\s*[0-9]+、"  逐条数编号链
#        pdftoppm -png -r 140 -f 1 -l 1 out.pdf prefix          转图发给Maggie确认

set -e
SRC="$1"
[ -z "$SRC" ] && { echo "用法: $0 <docx路径> [输出PDF]"; exit 1; }
OUT="${2:-${SRC%.docx}.pdf}"
CONTAINER=nextcloud-onlyoffice-1
TS=$(date +%s%N)
INNAME="/tmp/render_${TS}.docx"
OUTNAME="/tmp/render_${TS}.pdf"
CONVXML="/tmp/conv_${TS}.xml"

docker cp "$SRC" "${CONTAINER}:${INNAME}"
docker exec "$CONTAINER" bash -c "cat > ${CONVXML} << 'EOF'
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<TaskQueueDataConvert xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<m_sFileFrom>${INNAME}</m_sFileFrom>
<m_sFileTo>${OUTNAME}</m_sFileTo>
<m_bIsNoBase64>true</m_bIsNoBase64>
</TaskQueueDataConvert>
EOF
cd /var/www/onlyoffice/documentserver/server/FileConverter/bin && ./x2t ${CONVXML} > /dev/null 2>&1 && echo x2t_done"
docker cp "${CONTAINER}:${OUTNAME}" "$OUT"
docker exec "$CONTAINER" rm -f "$INNAME" "$OUTNAME" "$CONVXML" 2>/dev/null || true
echo "渲染完成: $OUT"
