#!/bin/bash
# 裝 FSE 本地 OCR worker（VPS 23.95.248.105）
# 前設：fse-ocr-worker.sh / fse-ocr-worker.service 已 upload 落 /root
# 呢支檔只做加法式改動：新增 /www/fse-ocr、一個 systemd 服務、一個設定檔；
# 唔碰 php.ini 嘅 disable_functions，亦唔碰網站 vhost ⇒ 唔使上載任何 project code 都得装。
set -euo pipefail

ROOT=/www/fse-ocr
SPOOL=/tmp/fse-ocr-spool
CONF=/www/fse-config/ocr_local.php

command -v tesseract >/dev/null || { echo "FAIL_NO_TESSERATE"; exit 1; }
tesseract --list-langs 2>&1 | grep -qx eng || { echo "FAIL_NO_ENG_LANG"; exit 1; }
echo "TESS=$(tesseract --version 2>&1 | head -1)"
findmnt -no FSTYPE,OPTIONS /tmp 2>/dev/null | sed 's/^/TMOUNT=/' || echo "TMOUNT=（睇唔到，假設可寫）"

mkdir -p "$ROOT"
install -m 0750 -o root -g www /root/fse-ocr-worker.sh "$ROOT/worker.sh"
install -m 0644 -o root -g root /root/fse-ocr-worker.service /etc/systemd/system/fse-ocr-worker.service
echo "FILES_INSTALLED"

systemctl daemon-reload
systemctl enable --now fse-ocr-worker
sleep 3
systemctl is-active fse-ocr-worker | sed 's/^/ACTIVE=/'
systemctl --no-pager --lines=6 status fse-ocr-worker | tail -8

# spool 由 worker 自己起（0700 www）；呢度只係確認 PHP 呢邊用唔用到
ls -ld "$SPOOL" "$SPOOL"/new "$SPOOL"/done "$SPOOL"/tmp 2>&1 | sed 's/^/SPOOL /'
[ -f "$SPOOL/heartbeat" ] && echo "HEARTBEAT=ok" || echo "HEARTBEAT=missing"

if [ -f "$CONF" ]; then
  echo "CONFIG_KEPT（已有設定檔，唔覆寫）"
else
  cat > "$CONF" <<'PHP'
<?php
/** FSE 本地 OCR（Tesseract）設定：worker 食紧呢個 spool 目錄 */
return [
    'enabled' => true,
    'dir' => '/tmp/fse-ocr-spool',
    'heartbeat' => 20,
];
PHP
  chown root:www "$CONF"
  chmod 640 "$CONF"
  echo "CONFIG_WRITTEN"
fi
ls -l "$CONF" | sed 's/^/CONF /'
echo "DONE"
