#!/bin/sh
# First-run initialization

mkdir -p /etc/mihomo/ui
chmod +x /usr/bin/mihomo 2>/dev/null

if ! uci -q get mihomo.config >/dev/null; then
	uci set mihomo.config='mihomo'
	uci set mihomo.config.enabled='0'
	uci commit mihomo
fi

# 安全:external-controller 默认监听 0.0.0.0:9090(供全屋设备开 Web 控制台),
# 没有 secret = 同网段任何设备都能控制内核 / 读全部连接。首次安装若 secret 为空,
# 生成一个随机 secret(用户无需管,LuCI 状态页可见并一键带入面板)。
secret=$(uci -q get mihomo.config.api_secret)
if [ -z "$secret" ]; then
	rnd=$(head -c 24 /dev/urandom 2>/dev/null | md5sum 2>/dev/null | cut -c1-24)
	[ -z "$rnd" ] && rnd=$(cat /proc/sys/kernel/random/uuid 2>/dev/null | tr -d '-')
	[ -z "$rnd" ] && rnd="apex$(date +%s)"
	uci set mihomo.config.api_secret="$rnd"
	uci commit mihomo
fi

# 【纵深防御 · 2026-08-23】/etc/config/mihomo 含 panel_password / xor_key /
# subscription_url(带 token) / api_secret,收紧到仅 root 可读(OpenWrt 默认 0644
# = world-readable)。commit 后再 chmod,确保最终态是 600。
chmod 600 /etc/config/mihomo 2>/dev/null

exit 0
