#!/bin/sh
mkdir -p /etc/lasersharp
if [ ! -s /etc/lasersharp/pairing_code ]; then
    CODE=$(awk 'BEGIN{srand(); printf "%06d", int(100000 + rand() * 900000)}')
    echo -n "$CODE" > /etc/lasersharp/pairing_code
fi
export HOME=/etc/lasersharp
PRINTER_ARG=""
if [ -s /etc/lasersharp/printer_ip ]; then
    PIP=$(cat /etc/lasersharp/printer_ip | tr -d ' \r\n')
    if [ -n "$PIP" ]; then
        PRINTER_ARG="--printer-ip $PIP"
    fi
fi
if command -v python3 >/dev/null 2>&1; then
    exec python3 /usr/bin/lasersharp-gateway.py --headless --web-port 19180 $PRINTER_ARG
else
    echo "[HawkEye] 正在自动通过 opkg 安装 python3-light 运行环境..." > /tmp/lasersharp_gateway.log
    opkg update >> /tmp/lasersharp_gateway.log 2>&1
    opkg install python3-light >> /tmp/lasersharp_gateway.log 2>&1
    if command -v python3 >/dev/null 2>&1; then
        exec python3 /usr/bin/lasersharp-gateway.py --headless --web-port 19180 $PRINTER_ARG
    else
        echo "[HawkEye] 尚未安装 python3-light，请在网页点击一键安装或运行: opkg update && opkg install python3-light" >> /tmp/lasersharp_gateway.log
        while true; do sleep 60; done
    fi
fi
