#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
VENVDIR="$SCRIPT_DIR/venv"

echo "== Printer_Screen_Menu 安装脚本 =="

if ! command -v apt >/dev/null 2>&1; then
  echo "错误：本脚本需要 apt（Debian/Ubuntu）。请在支持 apt 的系统上运行。"
  exit 1
fi

SUDO=""
if [ "$(id -u)" -ne 0 ]; then
  SUDO="sudo"
fi

echo "更新 apt 索引并安装基础包（python3-venv, python3-pip）..."
$SUDO apt-get update -y
$SUDO apt-get install -y python3-venv python3-pip

echo "检测可用的 PyQt6 apt 包并尝试通过 apt 安装（优先使用系统包）..."
pyqt_candidates=(
  python3-pyqt6
  python3-pyqt6.qt6-opengl
  python3-pyqt6.qtsvg
  python3-pyqt6.qt6widgets
  python3-pyqt6.qtopengl
  python3-pyqt6.qt6opengl
)
found_pyqt=()
for p in "${pyqt_candidates[@]}"; do
  if apt-cache show "$p" >/dev/null 2>&1; then
    found_pyqt+=("$p")
  fi
done

if [ "${#found_pyqt[@]}" -gt 0 ]; then
  echo "通过 apt 安装： ${found_pyqt[*]}"
  $SUDO apt-get install -y "${found_pyqt[@]}"
else
  echo "未检测到合适的 PyQt6 apt 包，将在虚拟环境内使用 pip 安装 PyQt6 作为回退。"
  install_pyqt_via_pip=1
fi

if apt-cache show python3-opengl >/dev/null 2>&1; then
  echo "检测到系统级 python3-opengl，尝试通过 apt 安装（可选加速）。"
  $SUDO apt-get install -y python3-opengl
else
  echo "未检测到 python3-opengl，PyOpenGL 将在虚拟环境中通过 pip 安装。"
fi

echo "创建虚拟环境（如果不存在）: $VENVDIR"
if [ ! -d "$VENVDIR" ]; then
  python3 -m venv "$VENVDIR"
else
  echo "虚拟环境已存在，跳过创建。"
fi

echo "激活虚拟环境并升级 pip..."
# shellcheck disable=SC1090
source "$VENVDIR/bin/activate"
python -m pip install --upgrade pip setuptools wheel

PYTHON_VERSION=$(ls $VENVDIR/lib/ | grep python3)


if [ "${install_pyqt_via_pip:-0}" = "1" ]; then
  echo "在 venv 中通过 pip 安装 PyQt6（回退）..."
  pip install PyQt6
else 
  echo "系统级 PyQt6 已安装，复制到虚拟环境中以供使用..."
  cp -r /usr/lib/python3/dist-packages/PyQt6 "$VENVDIR/lib/$PYTHON_VERSION/site-packages/"
  cp -r /usr/lib/python3/dist-packages/PyQt6-*.dist-info "$VENVDIR/lib/$PYTHON_VERSION/site-packages/"
  cp -r /usr/lib/python3/dist-packages/PyQt6_sip-*.dist-info "$VENVDIR/lib/$PYTHON_VERSION/site-packages/" || true
fi

REQ_FILE="$SCRIPT_DIR/requirements.txt"
if [ -f "$REQ_FILE" ]; then
  echo "通过 requirements.txt 安装 pip 依赖..."
  pip install -r "$REQ_FILE"
else
  echo "找不到 requirements.txt，安装常用依赖..."
  pip install requests numpy PyOpenGL qrcode Pillow
fi

echo "\n依赖安装完成。要使用本项目："
echo "1) 激活虚拟环境：source venv/bin/activate"
echo "2) 启动程序：python3 main.py"
echo "接下来进行 systemd 服务配置... (将会安装于 /opt/Printer_Screen_Menu)"


echo "Stopping existing service..."
systemctl disable printer-screen.service
systemctl stop printer-screen.service

echo "Cleaning up old installation..."
rm -rf /etc/systemd/system/printer-screen.service
rm -rf /opt/Printer_Screen_Menu

echo "Copying new files..."
mkdir -p /opt/Printer_Screen_Menu
cp -r ./. /opt/Printer_Screen_Menu/

echo "Setting up systemd service..."
chmod +x /opt/Printer_Screen_Menu/run.sh


cp printer-screen.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable printer-screen.service
systemctl start printer-screen.service

echo "Installation complete. Printer Screen Menu should now be running."