#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""BR Protocol Debug Tool —— 启动器

程序装在哪儿不由这里写死: postinst 把用户选定的安装目录写进
/etc/protocol-debug-tool.conf, 这里读出来再把它加进 sys.path。
读不到配置(比如手动解包、或配置文件被删)就用默认目录兜底。
"""

import os
import sys

DEFAULT_DIR = "/opt/apps/protocol-debug-tool"
CONF = "/etc/protocol-debug-tool.conf"

INSTALL_DIR = DEFAULT_DIR

try:
    # utf-8-sig: 用记事本之类的编辑器改过这个文件的话, 开头会多一个 BOM 字节,
    # 按 utf-8 读第一行会变成 "﻿INSTALL_DIR=...", startswith 匹配不上,
    # 于是静悄悄地退回默认目录 —— 明明选了自定义目录却起不来, 还看不出原因。
    # utf-8-sig 对"有 BOM"和"没 BOM"两种都认(postinst 写的是没 BOM 的)。
    with open(CONF, "r", encoding="utf-8-sig") as f:
        for line in f:
            line = line.strip()
            if line.startswith("INSTALL_DIR="):
                v = line.split("=", 1)[1].strip().strip('"').strip("'")
                if v:
                    INSTALL_DIR = v
                    break
except OSError:
    pass

if not os.path.isdir(INSTALL_DIR):
    print("错误: 找不到程序目录 %s" % INSTALL_DIR)
    print("      配置文件: %s" % CONF)
    print("      重装一次即可修复: sudo dpkg -i protocol-debug-tool_*.deb")
    sys.exit(1)

try:
    from PyQt5.QtWidgets import QApplication  # noqa: F401
except ImportError:
    print("错误: 需要 python3-pyqt5, 请执行: sudo apt-get install python3-pyqt5")
    sys.exit(1)

sys.path.insert(0, INSTALL_DIR)
os.chdir(INSTALL_DIR)

from main import main

sys.exit(main())
