This commit is contained in:
Arvin
2026-03-21 13:58:10 +08:00
parent f62ea80d43
commit dda67b180d
72 changed files with 848 additions and 1181 deletions

View File

@ -12,7 +12,9 @@ mkdir -p "$RUNTIME_DIR" "$LOG_DIR"
FOREGROUND=false
DAEMON=false
# 解析参数
# =========================
# 参数解析
# =========================
for arg in "$@"; do
case "$arg" in
--foreground) FOREGROUND=true ;;
@ -29,6 +31,14 @@ if [ "$FOREGROUND" = true ] && [ "$DAEMON" = true ]; then
exit 2
fi
if [ "$FOREGROUND" = false ] && [ "$DAEMON" = false ]; then
echo "[ERROR] Must specify --foreground or --daemon" >&2
exit 2
fi
# =========================
# 基础校验
# =========================
if [ ! -s "$CONFIG_FILE" ]; then
echo "[ERROR] runtime config not found: $CONFIG_FILE" >&2
exit 2
@ -39,6 +49,9 @@ if grep -q '\${' "$CONFIG_FILE"; then
exit 2
fi
# =========================
# 加载依赖
# =========================
# shellcheck disable=SC1091
source "$PROJECT_DIR/scripts/get_cpu_arch.sh"
# shellcheck disable=SC1091
@ -46,40 +59,49 @@ source "$PROJECT_DIR/scripts/resolve_clash.sh"
# shellcheck disable=SC1091
source "$PROJECT_DIR/scripts/service_lib.sh"
# =========================
# 获取二进制
# =========================
CLASH_BIN="$(resolve_clash_bin "$PROJECT_DIR" "${CpuArch:-}")"
if [ ! -x "$CLASH_BIN" ]; then
echo "[ERROR] clash binary not found or not executable: $CLASH_BIN" >&2
echo "[ERROR] clash binary not executable: $CLASH_BIN" >&2
exit 2
fi
test_config() {
local bin="$1"
local config="$2"
local runtime_dir="$3"
"$bin" -d "$runtime_dir" -t -f "$config" >/dev/null 2>&1
}
if ! test_config "$CLASH_BIN" "$CONFIG_FILE" "$RUNTIME_DIR"; then
echo "[ERROR] config test failed: $CONFIG_FILE" >&2
# =========================
# config 测试(唯一一次)
# =========================
if ! "$CLASH_BIN" -t -f "$CONFIG_FILE" -d "$RUNTIME_DIR" >/dev/null 2>&1; then
echo "[ERROR] clash config test failed: $CONFIG_FILE" >&2
write_run_state "failed" "config-test"
exit 2
fi
# systemd 模式
# =========================
# 前台模式systemd
# =========================
if [ "$FOREGROUND" = true ]; then
write_run_state "running" "systemd"
exec "$CLASH_BIN" -f "$CONFIG_FILE" -d "$RUNTIME_DIR"
fi
# script / daemon 模式
if [ "$DAEMON" = true ]; then
nohup "$CLASH_BIN" -f "$CONFIG_FILE" -d "$RUNTIME_DIR" >>"$LOG_DIR/clash.log" 2>&1 &
pid=$!
echo "$pid" > "$PID_FILE"
write_run_state "running" "script" "$pid"
echo "[OK] Clash started in script mode, pid=$pid"
# =========================
# 后台模式script
# =========================
cleanup_dead_pid
if is_script_running; then
pid="$(read_pid 2>/dev/null || true)"
echo "[INFO] clash already running, pid=${pid:-unknown}"
exit 0
fi
echo "[ERROR] Must specify --foreground or --daemon" >&2
exit 2
nohup "$CLASH_BIN" -f "$CONFIG_FILE" -d "$RUNTIME_DIR" >>"$LOG_DIR/clash.log" 2>&1 &
pid=$!
echo "$pid" > "$PID_FILE"
write_run_state "running" "script" "$pid"
echo "[OK] Clash started in script mode, pid=$pid"