mihomo-kit/router/mihomo-kit.sh

1137 lines
38 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/sh
# mihomo config kit for nikki on OpenWrt.
#
# Builds mihomo profiles from templates/ + per-profile env files, and keeps the
# router-side fixes in place (core version, Tailscale env, nikki bypass list).
#
# Layout on the router:
# /etc/nikki/kit/{templates,presets,router,luci} the kit (install.sh / update / tools/push.sh)
# /etc/nikki/profiles.d/common.env shared secrets/options
# /etc/nikki/profiles.d/<name>.env one file per profile (home, street, ...)
# /etc/nikki/profiles/<name>.yaml generated, what nikki runs
#
# Usage:
# mihomo-kit.sh setup [--cli] first run: install, then settings in LuCI
# (--cli or no LuCI: questions here + build + start)
# mihomo-kit.sh configure <env> settings from an env file (LuCI form) -> write, build, start
# mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all)
# mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart
# mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild
# mihomo-kit.sh check-update latest commit on the server vs the installed one
# mihomo-kit.sh update --apply update, then restart the current profile (and fix the core)
# mihomo-kit.sh auto-update [on|off] daily 04:00 update via cron; no argument = run it now
# mihomo-kit.sh fix re-apply core version + fixes (after a nikki upgrade)
# mihomo-kit.sh ts-login [-f] fresh Tailscale node, print its login URL
# (-f: also when the node is already logged in)
# mihomo-kit.sh install packages, core, fixes, links (no questions)
# mihomo-kit.sh render <env>... print the YAML for env file(s) (last wins)
set -u
# resolve the /usr/bin symlink to find the kit
SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
KIT_DIR="${KIT_DIR:-$(cd "$(dirname "$SELF")/.." && pwd)}"
TPL_DIR="${TPL_DIR:-$KIT_DIR/templates}"
NIKKI_DIR="${NIKKI_DIR:-/etc/nikki}"
PROFILES_D="$NIKKI_DIR/profiles.d"
PROFILES_OUT="$NIKKI_DIR/profiles"
: "${MIHOMO_VERSION:=v1.19.32}"
: "${KIT_URL:=https://git.sam-hub.net/sam/mihomo-kit/archive/main.tar.gz}"
log() { echo "$*" >&2; }
die() { log "error: $*"; exit 1; }
# --- rendering --------------------------------------------------------------
# Template syntax (same in web/engine.js):
# file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
# .each = once per item of the module:
# sub - subscription, hy2 - own server
# line ... #@tag[,!tag] kept only if the conditions hold
# line ... ${@VAR} ... repeated for every word of VAR
# line ... ${@@VAR} ... repeated for every line of VAR
# text ${VAR} replaced with the variable
set_defaults() {
: "${TARGET:=router}" "${LOCATION:=home}"
: "${BOOT:=1}" "${TORRENT:=1}" "${OPENVPN:=0}" "${TAILSCALE:=0}" "${TS_EXIT:=0}"
: "${SUBS:=}" "${RU_IPS:=}" "${HY2:=}"
: "${GEOIP_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geoip.dat}"
: "${GEOSITE_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geosite.dat}"
: "${BOOT_LINKS:=}"
: "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}"
: "${TS_HOSTNAME:=mihomo}" "${TS_DOMAINS:=}"
: "${HWID_UA:=v2rayN/9.99}" "${HWID_OS:=}" "${HWID_OS_VER:=}" "${HWID_MODEL:=}" "${HWID_ID:=}"
: "${OVPN_PROVIDER:=bmstu}" "${OVPN_GROUP:=BMSTU}" "${OVPN_SERVER_HOST:=openvpn4.bmstu.ru}"
: "${OVPN_SERVER_IPS:=195.19.40.7 195.19.33.86}"
: "${OVPN_ROUTES:=172.16.0.0/16 172.19.33.0/24 195.19.32.0/19}"
: "${OVPN_CHECK_URL:=https://eu.bmstu.ru}" "${TS_CHECK_URL:=http://100.69.216.50:8080}"
}
compute_tags() {
TAGS=" base sub $TARGET "
[ "$BOOT" = 1 ] && TAGS="$TAGS boot "
if [ "$TARGET" = router ]; then
TAGS="$TAGS $LOCATION "
[ "$TORRENT" = 1 ] && TAGS="$TAGS torrent "
[ "$OPENVPN" = 1 ] && TAGS="$TAGS openvpn "
if [ "$TAILSCALE" = 1 ]; then
TAGS="$TAGS tailscale "
[ "$TS_EXIT" = 1 ] && TAGS="$TAGS ts_exit "
fi
fi
SUB_LIST="" _i=0
for _p in $SUB_PAIRS; do
sub_off "$_i" "${_p%%=*}" || SUB_LIST="${SUB_LIST:+$SUB_LIST, }${_p%%=*}"
_i=$((_i + 1))
done
# own hysteria2 servers: HY2_LIST "a, b" (group MY), HY2_MAIN "MY, " (MAIN)
HY2_LIST="" HY2_MAIN=""
for _n in $HY2; do
HY2_LIST="${HY2_LIST:+$HY2_LIST, }$_n"
done
[ -n "$HY2" ] && TAGS="$TAGS hy2 " HY2_MAIN="MY, "
export SUB_LIST HY2_LIST HY2_MAIN
}
# vless_parse <vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name>
# -> _vs_server _vs_port _vs_uuid _vs_sni _vs_pbk _vs_sid (empty when missing)
vless_parse() {
_l=${1#vless://}
_l=${_l%%#*}
_vs_uuid=${_l%%@*}
_hp=${_l#*@}
_hp=${_hp%%\?*}
_vs_server=${_hp%:*}
_vs_port=${_hp##*:}
case "$_vs_port" in '' | *[!0-9]*) _vs_port=443 ;; esac
_q="&${_l#*\?}&"
_vs_sni=$(vless_qv sni) _vs_pbk=$(vless_qv pbk) _vs_sid=$(vless_qv sid)
}
vless_qv() { _v=${_q#*&$1=}; [ "$_v" = "$_q" ] || echo "${_v%%&*}"; }
# BOOT seeds: BOOT_LINKS (vless links, space/newline separated) or the old single
# BOOT_SERVER/PORT/UUID/SNI/PBK/SID -> SEED_ITEMS "name|server|port|uuid|sni|pbk|sid ...",
# SEED_LIST "seed, seed2". Same as bootSeeds() in web/engine.js.
boot_seeds() {
SEED_ITEMS="" SEED_LIST="" _k=1
if [ -n "$BOOT_LINKS" ]; then
set -f
for _l in $BOOT_LINKS; do
vless_parse "$_l"
_n=seed
[ "$_k" -gt 1 ] && _n=seed$_k
SEED_ITEMS="${SEED_ITEMS:+$SEED_ITEMS }$_n|$_vs_server|$_vs_port|$_vs_uuid|$_vs_sni|$_vs_pbk|$_vs_sid"
_k=$((_k + 1))
done
set +f
elif [ -n "$BOOT_SERVER" ]; then
SEED_ITEMS="seed|$BOOT_SERVER|$BOOT_PORT|$BOOT_UUID|$BOOT_SNI|$BOOT_PBK|$BOOT_SID"
fi
for _it in $SEED_ITEMS; do
SEED_LIST="${SEED_LIST:+$SEED_LIST, }${_it%%|*}"
done
export SEED_LIST
}
# seed_vars <item>: variables for templates/proxies/*-boot.each.yaml
seed_vars() {
_old_ifs=$IFS
IFS='|'
# shellcheck disable=SC2086
set -- $1
IFS=$_old_ifs
SEED_NAME=$1 SEED_SERVER=${2:-} SEED_PORT=${3:-} SEED_UUID=${4:-} SEED_SNI=${5:-} SEED_PBK=${6:-} SEED_SID=${7:-}
export SEED_NAME SEED_SERVER SEED_PORT SEED_UUID SEED_SNI SEED_PBK SEED_SID
}
# Subscription ids (provider names, keys SUB_<ID>_*). A SUBS word is "url" or
# "name=url"; without a name the id comes from the domain:
# https://sub.kittyvpn.com/x -> kittyvpn, https://a.b.co.uk/ -> b
# Repeats get 2, 3, ... Same algorithm as subPairs() in web/engine.js.
sub_auto_id() {
_h=${1#*://}
_h=${_h%%[/?#]*}
_h=${_h##*@}
_h=$(printf '%s' "${_h%:*}" | tr 'A-Z' 'a-z')
case "$_h" in *.*) _h=${_h%.*} ;; esac
while :; do
case "$_h" in
*.co | *.com | *.net | *.org | *.gov | *.edu | *.ac) _h=${_h%.*} ;;
*) break ;;
esac
done
_h=$(printf '%s' "${_h##*.}" | sed 's/[^a-z0-9_]/_/g')
case "$_h" in
'') echo sub ;;
[0-9]*) echo "sub$_h" ;;
*) echo "$_h" ;;
esac
}
# SUBS -> SUB_PAIRS="id=url id=url ..."
sub_pairs() {
SUB_PAIRS="" _seen=" "
set -f
for _w in $SUBS; do
_n=${_w%%=*} _u=${_w#*=}
case "$_n" in "$_w" | '' | *[!A-Za-z0-9_-]*) _n=$(sub_auto_id "$_w") _u=$_w ;; esac
_n=$(printf '%s' "$_n" | tr 'A-Z-' 'a-z_')
_id=$_n _k=2
while case "$_seen" in *" $_id "*) true ;; *) false ;; esac; do
_id=$_n$_k _k=$((_k + 1))
done
_seen="$_seen$_id "
SUB_PAIRS="${SUB_PAIRS:+$SUB_PAIRS }$_id=$_u"
done
set +f
}
# sub_get <index> <id> <KEY>: SUB_<ID>_<KEY>, else the old SUB<index>_<KEY>
sub_get() {
_K=$(printf '%s' "$2" | tr 'a-z' 'A-Z')
eval "printf '%s' \"\${SUB_${_K}_$3:-\${SUB$1_$3:-}}\""
}
# sub_off <index> <id>: SUB_<ID>_DISABLED=1 keeps the subscription (id, settings)
# but leaves it out of the profile
sub_off() { [ "$(sub_get "$1" "$2" DISABLED)" = 1 ]; }
check_vars() {
[ -n "$SUBS" ] || die "SUBS is empty (subscription URLs)"
case "$TARGET" in router | mobile) ;; *) die "TARGET must be router or mobile" ;; esac
case "$LOCATION" in home | street) ;; *) die "LOCATION must be home or street" ;; esac
if [ "$BOOT" = 1 ]; then
[ -n "$SEED_ITEMS" ] || die "BOOT=1 but no BOOT_LINKS (vless links of the seed nodes)"
for _it in $SEED_ITEMS; do
seed_vars "$_it"
for v in SERVER UUID SNI PBK SID; do
eval "[ -n \"\$SEED_$v\" ]" || die "BOOT $SEED_NAME: $v is empty (vless link needs host, uuid, sni, pbk, sid)"
done
done
fi
i=0 _on=0
for _pr in $SUB_PAIRS; do
_id=${_pr%%=*}
if sub_off "$i" "$_id"; then
i=$((i + 1))
continue
fi
_on=1
case "$(sub_get "$i" "$_id" PROXY)" in
BOOT | BOOT-AUTO) [ "$BOOT" = 1 ] || die "subscription $_id: PROXY=BOOT but BOOT=0" ;;
esac
if [ "$(sub_get "$i" "$_id" HWID)" = 1 ]; then
for v in HWID_OS HWID_OS_VER HWID_MODEL HWID_ID; do
eval "[ -n \"\${$v}\" ]" || die "$v is empty (subscription $_id has HWID=1)"
done
fi
i=$((i + 1))
done
[ "$_on" = 1 ] || die "all subscriptions are disabled (SUB_<ID>_DISABLED=1)"
for _n in $HY2; do
case "$_n" in *[!A-Za-z0-9_-]*) die "HY2: bad server name $_n (letters, digits, _ -)" ;; esac
_k=$(hy2_key "$_n")
for v in SERVER PORT PASSWORD; do
eval "[ -n \"\${${_k}_$v:-}\" ]" || die "${_k}_$v is empty (hysteria2 server $_n)"
done
done
}
# hy2_key <name>: HY2_<NAME> prefix of the server's keys (upper case, - -> _)
hy2_key() { printf 'HY2_%s' "$(printf '%s' "$1" | tr 'a-z-' 'A-Z_')"; }
# YAML double-quoted string body
yq() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }
# per-subscription variables for the .each templates: sub_vars <index> <id> <url>
# (ID = id in upper case; the old SUB<index>_* keys still work)
# SUB_<ID>_PROXY BOOT-AUTO (default with BOOT=1) | BOOT | DIRECT | FOREIGN | any proxy/group | none
# SUB_<ID>_UA User-Agent (default mihomo, with HWID: HWID_UA)
# SUB_<ID>_HWID=1 send x-device-os / x-ver-os / x-device-model / x-hwid from HWID_*
# SUB_<ID>_HEADERS extra headers: "key=value; key2=value 2"
sub_vars() {
SUB_NAME="$2" SUB_URL="$3"
_p=$(sub_get "$1" "$2" PROXY) _ua=$(sub_get "$1" "$2" UA) _hw=$(sub_get "$1" "$2" HWID)
_h=$(sub_get "$1" "$2" HEADERS)
[ -z "$_p" ] && [ "$BOOT" = 1 ] && _p=BOOT-AUTO
[ "$_p" = none ] && _p=""
if [ "$_hw" = 1 ]; then
[ -n "$_ua" ] || _ua=$HWID_UA
_h="x-device-os=$HWID_OS;x-ver-os=$HWID_OS_VER;x-device-model=$HWID_MODEL;x-hwid=$HWID_ID${_h:+;$_h}"
fi
SUB_PROXY=$_p
SUB_UA=$(yq "${_ua:-mihomo}")
SUB_HEADERS=""
_old_ifs=$IFS
IFS=';'
set -f
for _item in $_h; do
_item=$(printf '%s' "$_item" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
[ -n "$_item" ] || continue
_k=$(printf '%s' "${_item%%=*}" | sed 's/[[:space:]]*$//')
_v=$(printf '%s' "${_item#*=}" | sed 's/^[[:space:]]*//')
SUB_HEADERS="${SUB_HEADERS:+$SUB_HEADERS
}$_k: [\"$(yq "$_v")\"]"
done
set +f
IFS=$_old_ifs
export SUB_NAME SUB_URL SUB_PROXY SUB_UA SUB_HEADERS
}
# variables for templates/proxies/*-hy2.each.yaml: hy2_vars <name>
# HY2_<NAME>_SERVER, _PORT, _PASSWORD required
# HY2_<NAME>_OBFS_PASSWORD salamander obfs (empty = none)
# HY2_<NAME>_SNI, _INSECURE=1 (skip-cert-verify), _UP, _DOWN ("50 mbps")
hy2_vars() {
_k=$(hy2_key "$1")
eval "HY2_SERVER=\${${_k}_SERVER} HY2_PORT=\${${_k}_PORT} _pw=\${${_k}_PASSWORD}
_ob=\${${_k}_OBFS_PASSWORD:-} HY2_SNI=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0}
_up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}"
HY2_NAME=$1
HY2_PASSWORD=$(yq "$_pw")
HY2_OBFS="" HY2_OBFS_PASSWORD=""
[ -n "$_ob" ] && HY2_OBFS=salamander HY2_OBFS_PASSWORD=$(yq "$_ob")
HY2_INSECURE=false
[ "$_in" = 1 ] && HY2_INSECURE=true
HY2_UP=$(yq "$_up") HY2_DOWN=$(yq "$_dn")
export HY2_NAME HY2_SERVER HY2_PORT HY2_PASSWORD HY2_OBFS HY2_OBFS_PASSWORD HY2_SNI \
HY2_INSECURE HY2_UP HY2_DOWN
}
render_file() {
awk -v tags="$TAGS" '
function active(c, neg) {
neg = 0
if (substr(c, 1, 1) == "!") { neg = 1; c = substr(c, 2) }
return (index(tags, " " c " ") > 0) != neg
}
function subst(s, out, i, j) {
out = ""
while ((i = index(s, "${")) > 0) {
j = index(substr(s, i + 2), "}")
if (j == 0) break
out = out substr(s, 1, i - 1) ENVIRON[substr(s, i + 2, j - 1)]
s = substr(s, i + 2 + j)
}
return out s
}
{
line = $0
if ((p = index(line, "#@")) > 0) {
n = split(substr(line, p + 2), cs, ",")
line = substr(line, 1, p - 1)
sub(/[ \t]+$/, "", line)
for (k = 1; k <= n; k++) if (!active(cs[k])) next
}
if ((i = index(line, "${@@")) > 0) {
j = index(substr(line, i + 4), "}")
pre = substr(line, 1, i - 1)
post = substr(line, i + 4 + j)
n = split(ENVIRON[substr(line, i + 4, j - 1)], ws, "\n")
for (k = 1; k <= n; k++) if (ws[k] != "") print subst(pre ws[k] post)
next
}
if ((i = index(line, "${@")) > 0) {
j = index(substr(line, i + 3), "}")
pre = substr(line, 1, i - 1)
post = substr(line, i + 3 + j)
n = split(ENVIRON[substr(line, i + 3, j - 1)], ws, /[ \t\n]+/)
for (k = 1; k <= n; k++) if (ws[k] != "") print subst(pre ws[k] post)
next
}
print subst(line)
}' "$1"
}
# is "<module>.<tag>...[.each]" active? sets EACH
fragment_active() {
EACH=0
_mod=${1%%.*}
case "$TAGS" in *" $_mod "*) ;; *) return 1 ;; esac
_rest=${1#"$_mod"}
_old_ifs=$IFS
IFS=.
for _t in $_rest; do
[ -z "$_t" ] && continue
if [ "$_t" = each ]; then EACH=1; continue; fi
case "$TAGS" in *" $_t "*) ;; *) IFS=$_old_ifs; return 1 ;; esac
done
IFS=$_old_ifs
return 0
}
render_section() {
_out=""
for f in "$TPL_DIR/$1"/*.yaml; do
[ -f "$f" ] || continue
_name=${f##*/}
_name=${_name%.yaml}
fragment_active "${_name#*-}" || continue
if [ "$EACH" = 1 ] && [ "$_mod" = boot ]; then
for _it in $SEED_ITEMS; do
seed_vars "$_it"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
done
elif [ "$EACH" = 1 ] && [ "$_mod" = hy2 ]; then
for _n in $HY2; do
hy2_vars "$_n"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
done
elif [ "$EACH" = 1 ]; then
i=0
for _pr in $SUB_PAIRS; do
if ! sub_off "$i" "${_pr%%=*}"; then
sub_vars "$i" "${_pr%%=*}" "${_pr#*=}"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
fi
i=$((i + 1))
done
else
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
fi
done
[ -n "$_out" ] || return 0
[ -n "${2:-}" ] && printf "%s\n" "$2"
printf "%s\n" "$_out"
}
render() {
set_defaults
sub_pairs
boot_seeds
check_vars
compute_tags
export TARGET LOCATION GEOIP_URL GEOSITE_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \
BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \
OVPN_SERVER_IPS OVPN_ROUTES RU_IPS OVPN_CHECK_URL TS_CHECK_URL
_first=1
for s in head proxies:proxies providers:proxy-providers sniffer dns groups:proxy-groups rules:rules; do
_dir=${s%%:*}
_hdr=""
[ "$_dir" != "$s" ] && _hdr="${s#*:}:"
_sec=$(render_section "$_dir" "$_hdr")
[ -n "$_sec" ] || continue
[ "$_first" = 1 ] || echo
printf "%s\n" "$_sec"
_first=0
done
}
load_env() {
for e in "$@"; do
[ -f "$e" ] || die "no env file $e"
set -a
. "$e"
set +a
done
}
cmd_render() {
[ $# -gt 0 ] || die "usage: render <env>..."
load_env "$@"
render
}
cmd_build() {
[ -d "$PROFILES_D" ] || die "no $PROFILES_D (see profile.env.example)"
mkdir -p "$PROFILES_OUT"
if [ $# -eq 0 ]; then
for e in "$PROFILES_D"/*.env; do
n=${e##*/}
n=${n%.env}
[ "$n" = common ] || set -- "$@" "$n"
done
fi
for n in "$@"; do
out="$PROFILES_OUT/$n.yaml"
envs="$PROFILES_D/$n.env"
[ -f "$PROFILES_D/common.env" ] && envs="$PROFILES_D/common.env $envs"
# subshell: profiles must not leak variables into each other
# shellcheck disable=SC2086
if (cmd_render $envs) > "$out.tmp"; then
mv "$out.tmp" "$out"
log "built $out"
if command -v mihomo >/dev/null 2>&1; then
mihomo -t -d "$NIKKI_DIR/run" -f "$out" >/dev/null 2>&1 ||
log "warning: mihomo -t failed for $out (run: mihomo -t -d $NIKKI_DIR/run -f $out)"
fi
else
rm -f "$out.tmp"
die "build of $n failed"
fi
done
}
cmd_use() {
[ $# -eq 1 ] || die "usage: use <name>"
[ -f "$PROFILES_OUT/$1.yaml" ] || die "no $PROFILES_OUT/$1.yaml, run build first"
uci set nikki.config.profile="file:$1.yaml"
uci commit nikki
/etc/init.d/nikki restart
log "nikki now runs $1"
if grep -q "^OPENVPN=1" "$PROFILES_D/$1.env" "$PROFILES_D/common.env" 2>/dev/null &&
command -v bmstu-otp.sh >/dev/null 2>&1; then
sleep 5
bmstu-otp.sh refresh
fi
}
# --- Tailscale login --------------------------------------------------------
TS_DIR="$NIKKI_DIR/run/tailscale"
CORE_LOG=/var/log/nikki/core.log
# mihomo API from nikki's mixin settings (same as bmstu-otp.sh)
api_get() {
l=$(uci -q get nikki.mixin.api_listen)
port=${l##*:} host=${l%:*}
case "$port" in '' | *[!0-9]*) port=9090 ;; esac
case "$host" in '' | 0.0.0.0 | '[::]' | '::' | '*' | "$l") host=127.0.0.1 ;; esac
sec=$(uci -q get nikki.mixin.api_secret)
path=$1
shift
curl -fsS -m 15 ${sec:+-H "Authorization: Bearer $sec"} "$@" "http://$host:$port$path"
}
ts_logged_in() {
grep -q '_current-profile' "$TS_DIR/tailscaled.state" 2>/dev/null
}
# The node starts on first use and prints the login URL once, at info level.
# A failed first start leaves a half-made state that stays silent, so start
# from an empty state dir with the log at info.
cmd_ts_login() {
if [ "${1:-}" != -f ] && ts_logged_in; then
log "Tailscale node is already logged in (ts-login -f to start over)"
return 0
fi
lvl=$(uci -q get nikki.mixin.log_level)
case "$lvl" in info | debug) ;; *) uci set nikki.mixin.log_level=info; uci commit nikki ;; esac
/etc/init.d/nikki stop
rm -rf "${TS_DIR:?}"
skip=$(wc -l < "$CORE_LOG" 2>/dev/null || echo 0)
/etc/init.d/nikki start
url=
i=0
while [ $i -lt 12 ]; do
i=$((i + 1))
# nikki may truncate the log on start
[ "$(wc -l < "$CORE_LOG" 2>/dev/null || echo 0)" -lt "$skip" ] && skip=0
url=$(tail -n "+$((skip + 1))" "$CORE_LOG" 2>/dev/null |
sed -n 's/.*To start this tsnet server.* go to: \(https:[^ "]*\).*/\1/p' | tail -n 1)
[ -n "$url" ] && break
# any dial through the node starts it
api_get /proxies/TAILSCALE/delay -G --data-urlencode "url=http://100.100.100.100/" \
--data-urlencode timeout=5000 >/dev/null 2>&1 || sleep 5
done
if [ "$lvl" != "$(uci -q get nikki.mixin.log_level)" ]; then
uci set nikki.mixin.log_level="${lvl:-warning}"
uci commit nikki
fi
if [ -z "$url" ]; then
log "no login URL in $CORE_LOG; check: grep '\[Tailscale\]' $CORE_LOG"
return 1
fi
{
echo "Tailscale: войди по ссылке, потом в админке Tailscale — Disable key expiry для ноды"
echo " $url"
} >&2
}
# --- router setup -----------------------------------------------------------
core_update() {
cur=$(mihomo -v 2>/dev/null | awk '{print $3; exit}')
if [ "$cur" = "$MIHOMO_VERSION" ]; then
log "mihomo core is $cur"
return 0
fi
case "$(uname -m)" in
aarch64) arch=arm64 ;;
x86_64) arch=amd64 ;;
armv7l) arch=armv7 ;;
mips) arch=mips-softfloat ;;
mipsel | mipsle) arch=mipsle-softfloat ;;
*) die "unknown arch $(uname -m), set the core manually" ;;
esac
url="https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-$arch-$MIHOMO_VERSION.gz"
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
curl -fL -o /tmp/mihomo.gz "$url" || die "download failed: $url"
gunzip -f /tmp/mihomo.gz && chmod +x /tmp/mihomo || die "unpack failed"
bin=$(command -v mihomo || echo /usr/bin/mihomo)
[ -f "$bin" ] && cp "$bin" "$bin.bak"
mv /tmp/mihomo "$bin"
log "core: $(mihomo -v | head -n 1)"
}
# Tailscale control over port 80 gets broken by the ISP: force 443.
patch_init() {
f=/etc/init.d/nikki
if grep -q TS_FORCE_NOISE_443 "$f"; then
log "init script already has TS_FORCE_NOISE_443"
elif grep -q "procd_append_param env SKIP_SYSTEM_IPV6_CHECK" "$f"; then
sed -i '/procd_append_param env SKIP_SYSTEM_IPV6_CHECK/a\ procd_append_param env TS_FORCE_NOISE_443=true' "$f"
log "added TS_FORCE_NOISE_443 to $f"
else
log "warning: anchor not found in $f, add 'procd_append_param env TS_FORCE_NOISE_443=true' by hand"
fi
}
# nikki skips these ranges before mihomo; Tailscale (100.64/10) and the
# OpenVPN internal nets (172.16/12) must reach mihomo rules.
fix_reserved() {
for net in 100.64.0.0/10 172.16.0.0/12; do
uci -q del_list nikki.proxy.reserved_ip="$net" && log "removed $net from nikki reserved_ip"
done
uci commit nikki
}
# Wired WAN first: wan/wan6 metric 10, other uplinks (modems, wifi client)
# 50, 60, ... in uci order. Interfaces with a metric already set are left alone.
wan_metrics() {
_changed=0 _m=50
for _if in $(uci -q show network | sed -n 's/^network\.\([^.=]*\)=interface$/\1/p'); do
case "$_if" in lan | loopback) continue ;; esac
case "$(uci -q get "network.$_if.proto")" in
dhcp | dhcpv6 | pppoe | qmi | mbim | ncm | 3g | modemmanager | qcm | wwan) ;;
*) continue ;;
esac
case "$_if" in
wan | wan6) _want=10 ;;
*) _want=$_m _m=$((_m + 10)) ;;
esac
[ -n "$(uci -q get "network.$_if.metric")" ] && continue
uci set "network.$_if.metric=$_want"
log "network.$_if.metric=$_want"
_changed=1
done
[ "$_changed" = 1 ] || return 0
uci commit network
/etc/init.d/network reload
}
install_files() {
for s in mihomo-kit.sh bmstu-otp.sh; do
chmod +x "$KIT_DIR/router/$s"
ln -sf "$KIT_DIR/router/$s" "/usr/bin/$s"
done
mkdir -p "$PROFILES_D"
chmod 700 "$PROFILES_D"
install_luci
}
# LuCI page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view.
# The view goes to view/mihomo-kit/v<hash>.js and the menu points there: LuCI
# loads views by script with a ?v= of its own version, which neither a kit
# update nor a hard reload changes, so a fixed name stays cached in the browser.
install_luci() {
src=$KIT_DIR/luci
[ -d "$src" ] && [ -d /www/luci-static/resources ] || return 0
_changed=0 _rpcd=0
# put <src> <dst> <mode>; uhttpd answers 403 for files that are not world-readable,
# and a run from LuCI inherits rpcd's umask 077
put() {
if ! cmp -s "$1" "$2"; then
mkdir -p "$(dirname "$2")"
cp "$1" "$2"
_changed=1
fi
chmod "$3" "$2"
}
put "$src/rpcd.sh" /usr/libexec/rpcd/mihomo-kit 755
put "$src/acl.json" /usr/share/rpcd/acl.d/luci-app-mihomo-kit.json 644
# rpcd needs a restart only for its plugin and ACL (it drops LuCI sessions)
_rpcd=$_changed
_views=/www/luci-static/resources/view
_v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8)
put "$src/mihomo-kit.js" "$_views/mihomo-kit/$_v.js" 644
for _f in "$_views/mihomo-kit.js" "$_views"/mihomo-kit/*.js; do
[ -f "$_f" ] && [ "$_f" != "$_views/mihomo-kit/$_v.js" ] && rm -f "$_f" && _changed=1
done
sed "s|\"path\": \"mihomo-kit\"|\"path\": \"mihomo-kit/$_v\"|" "$src/menu.json" > /tmp/mihomo-kit-menu.json
put /tmp/mihomo-kit-menu.json /usr/share/luci/menu.d/luci-app-mihomo-kit.json 644
rm -f /tmp/mihomo-kit-menu.json
[ "$_changed" = 1 ] || return 0
rm -rf /tmp/luci-indexcache* /tmp/luci-modulecache
log "LuCI page installed: Services -> mihomo-kit"
[ "$_rpcd" = 1 ] || return 0
# rpcd loads plugins only on start; delayed so a job started from LuCI
# (kit update) gets to finish first
(sleep 5; /etc/init.d/rpcd restart) < /dev/null > /dev/null 2>&1 &
}
enable_otp_cron() {
grep -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null && return 0
echo '* * * * * /usr/bin/bmstu-otp.sh check' >> /etc/crontabs/root
/etc/init.d/cron restart
log "added bmstu-otp.sh check to cron"
}
cmd_install() {
opkg update
if [ ! -x /etc/init.d/nikki ]; then
wget -O - https://github.com/nikkinikki-org/OpenWrt-nikki/raw/refs/heads/main/feed.sh | ash
opkg install nikki luci-app-nikki
fi
for p in curl oath-toolkit; do
opkg list-installed | grep -q "^$p " || opkg install "$p"
done
# curl newer than libcurl -> "Error relocating ... symbol not found"
curl --version >/dev/null 2>&1 || opkg install --force-reinstall libcurl4 curl
install_files
cmd_fix
}
cmd_fix() {
/etc/init.d/nikki stop 2>/dev/null
core_update
patch_init
fix_reserved
wan_metrics
/etc/init.d/nikki start
}
# --- setup wizard -----------------------------------------------------------
: "${TTY_IN:=/dev/tty}" "${TTY_OUT:=/dev/tty}"
# ask VAR "question" [default]
ask() {
printf '%s%s: ' "$2" "${3:+ [$3]}" > "$TTY_OUT"
read -r _a < "$TTY_IN" || _a=""
eval "$1=\${_a:-\${3:-}}"
}
# ask_secret VAR "question" (no echo)
ask_secret() {
printf '%s: ' "$2" > "$TTY_OUT"
stty -echo < "$TTY_IN" 2>/dev/null
read -r _a < "$TTY_IN" || _a=""
stty echo < "$TTY_IN" 2>/dev/null
echo > "$TTY_OUT"
eval "$1=\$_a"
}
# yesno VAR "question" y|n -> VAR=1|0
yesno() {
while :; do
ask _yn "$2 (y/n)" "$3"
case "$_yn" in
y | Y | yes | д | Д) eval "$1=1"; return ;;
n | N | no | н | Н) eval "$1=0"; return ;;
esac
done
}
# check_boot_links: every BOOT_LINKS link parses (host, uuid, sni, pbk, sid)
check_boot_links() {
set -f
for _l in $BOOT_LINKS; do
vless_parse "$_l"
[ -n "$_vs_server" ] && [ -n "$_vs_uuid" ] && [ -n "$_vs_sni" ] && [ -n "$_vs_pbk" ] && [ -n "$_vs_sid" ] ||
die "не разобрал vless-ссылку (нужны host, uuid, sni, pbk, sid): ${_l%%\?*}"
done
set +f
}
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
wizard() {
{
echo
echo "== mihomo-kit: профиль роутера =="
echo "Ответы сохранятся в $PROFILES_D/common.env (chmod 600)."
echo
} > "$TTY_OUT"
ask BOOT_LINKS "BOOT: vless:// ссылки seed-нод через пробел (пусто = без BOOT)"
BOOT=0
if [ -n "$BOOT_LINKS" ]; then
check_boot_links
BOOT=1
fi
echo "Подписки: по одной; пустой URL — конец." > "$TTY_OUT"
SUBS="" _n=0 _any_hwid=0
while :; do
ask _u "sub$_n URL"
[ -n "$_u" ] || break
SUBS="${SUBS:+$SUBS }$_u"
if [ "$BOOT" = 1 ]; then
ask _p " качать через (BOOT-AUTO/BOOT/DIRECT/FOREIGN)" BOOT-AUTO
else
_p=DIRECT
fi
eval "SUB${_n}_PROXY=\$_p"
yesno _hw " HWID-заголовки (x-hwid, x-device-os, ...; для подписок с лимитом устройств)" n
eval "SUB${_n}_HWID=\$_hw"
[ "$_hw" = 1 ] && _any_hwid=1
_n=$((_n + 1))
done
[ -n "$SUBS" ] || die "нужна хотя бы одна подписка"
if [ "$_any_hwid" = 1 ]; then
echo "HWID (общий для всех подписок с HWID):" > "$TTY_OUT"
[ -f /etc/openwrt_release ] && . /etc/openwrt_release
ask HWID_UA " User-Agent" "v2rayN/9.99"
ask HWID_OS " x-device-os" "OpenWrt"
ask HWID_OS_VER " x-ver-os" "${DISTRIB_RELEASE:-}"
ask HWID_MODEL " x-device-model" "$(cat /tmp/sysinfo/model 2>/dev/null)"
ask HWID_ID " x-hwid (если провайдер уже знает устройство — тот же)" \
"$(cat /sys/class/net/br-lan/address 2>/dev/null | md5sum | cut -c1-16)"
fi
yesno TORRENT "Торренты через TORRENT-SEL (порты 20000-20199)" y
ask RU_IPS "Доп. IP через RU (CIDR через пробел)" ""
yesno OPENVPN "OpenVPN BMSTU" n
if [ "$OPENVPN" = 1 ]; then
while [ ! -f "$NIKKI_DIR/bmstu.ovpn" ]; do
ask _dummy "Положи .ovpn в $NIKKI_DIR/bmstu.ovpn (scp -O file.ovpn root@router:$NIKKI_DIR/bmstu.ovpn) и нажми Enter"
done
ask VPN_USERNAME " логин"
ask_secret VPN_PASSWORD " пароль (без OTP)"
ask_secret TOTP_SECRET " TOTP-секрет (base32 из QR)"
fi
yesno TAILSCALE "Tailscale" n
if [ "$TAILSCALE" = 1 ]; then
ask TS_HOSTNAME " имя ноды" "$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo"
ask TS_DOMAINS " split-DNS домены тейлнета кроме *.ts.net (через пробел)" ""
fi
write_config
}
# keys write_config owns; any other KEY=value lines (added by hand) are kept
COMMON_KEYS='TARGET|SUBS|SUB[0-9]*_[A-Z0-9_]*(PROXY|HWID|DISABLED)|HWID_[A-Z_]+|BOOT|BOOT_[A-Z]+|TORRENT|RU_IPS|OPENVPN|TAILSCALE|TS_HOSTNAME|TS_DOMAINS'
VPN_KEYS='VPN_USERNAME|VPN_PASSWORD|TOTP_SECRET'
# other_keys <file> <keys-regex>
other_keys() {
grep -E '^[A-Za-z_][A-Za-z0-9_]*=' "$1" 2>/dev/null | grep -vE "^($2)="
}
# hand-added keys of common.env; the old SUB<index>_* ones are renamed to
# SUB_<ID>_* by the subscription order of that file
common_other_keys() {
_f=$PROFILES_D/common.env
[ -f "$_f" ] || return 0
_old_ids=$(
SUBS=
. "$_f"
sub_pairs
for _p in $SUB_PAIRS; do echo "${_p%%=*}"; done
)
other_keys "$_f" "$COMMON_KEYS" | while IFS= read -r _l; do
_n=${_l%%_*}
_n=${_n#SUB}
case "$_l" in
SUB[0-9]*_*)
case "$_n" in
'' | *[!0-9]*) ;;
*)
_id=$(echo "$_old_ids" | sed -n "$((_n + 1))p")
[ -n "$_id" ] && _l="SUB_$(echo "$_id" | tr 'a-z' 'A-Z')_${_l#*_}"
;;
esac
;;
esac
echo "$_l"
done
}
# common.env (+ bmstu.env) from the variables the wizard / configure set;
# per-subscription values come as SUB<index>_PROXY/HWID (index in SUBS).
# Keys only the LuCI form sets (own hysteria2 servers HY2, HY2_<NAME>_*, check
# URLs) are rewritten only with FORM=1; the terminal wizard keeps them.
write_config() {
umask 077
_any_hwid=0
[ "${FORM:-0}" = 1 ] && COMMON_KEYS="$COMMON_KEYS|HY2|HY2_[A-Z0-9_]+|OVPN_CHECK_URL|TS_CHECK_URL"
_others=$(common_other_keys)
sub_pairs
{
echo "# written by mihomo-kit.sh (setup / LuCI); edit and run: mihomo-kit.sh build"
echo "TARGET=router"
echo "SUBS=$(q "$SUBS")"
_i=0
for _pr in $SUB_PAIRS; do
_K=$(echo "${_pr%%=*}" | tr 'a-z' 'A-Z')
_p=$(sub_get "$_i" "${_pr%%=*}" PROXY) _hw=$(sub_get "$_i" "${_pr%%=*}" HWID)
case "$_p" in BOOT | BOOT-AUTO) [ "$BOOT" = 1 ] || _p=DIRECT ;; esac
[ -n "$_p" ] && [ "$_p" != BOOT-AUTO ] && echo "SUB_${_K}_PROXY=$(q "$_p")"
[ "$_hw" = 1 ] && echo "SUB_${_K}_HWID=1" && _any_hwid=1
sub_off "$_i" "${_pr%%=*}" && echo "SUB_${_K}_DISABLED=1"
_i=$((_i + 1))
done
if [ "$_any_hwid" = 1 ]; then
for v in HWID_UA HWID_OS HWID_OS_VER HWID_MODEL HWID_ID; do
eval "echo \"$v=\$(q \"\${$v:-}\")\""
done
fi
echo "BOOT=$BOOT"
[ "$BOOT" = 1 ] && echo "BOOT_LINKS=$(q "$BOOT_LINKS")"
echo "TORRENT=$TORRENT"
echo "RU_IPS=$(q "$RU_IPS")"
echo "OPENVPN=$OPENVPN"
echo "TAILSCALE=$TAILSCALE"
[ "$TAILSCALE" = 1 ] && echo "TS_HOSTNAME=$(q "$TS_HOSTNAME")" && echo "TS_DOMAINS=$(q "$TS_DOMAINS")"
if [ "${FORM:-0}" = 1 ]; then
[ -n "${OVPN_CHECK_URL:-}" ] && echo "OVPN_CHECK_URL=$(q "$OVPN_CHECK_URL")"
[ -n "${TS_CHECK_URL:-}" ] && echo "TS_CHECK_URL=$(q "$TS_CHECK_URL")"
echo "HY2=$(q "$HY2")"
for _n in $HY2; do
_k=$(hy2_key "$_n")
for v in SERVER PORT PASSWORD OBFS_PASSWORD SNI INSECURE UP DOWN; do
eval "_v=\${${_k}_$v:-}"
[ -n "$_v" ] && echo "${_k}_$v=$(q "$_v")"
done
done
fi
[ -n "$_others" ] && echo "$_others"
true
} > "$PROFILES_D/common.env.tmp" && mv "$PROFILES_D/common.env.tmp" "$PROFILES_D/common.env"
if [ "$OPENVPN" = 1 ]; then
{
echo "# written by mihomo-kit.sh (setup / LuCI)"
echo "VPN_USERNAME=$(q "$VPN_USERNAME")"
echo "VPN_PASSWORD=$(q "$VPN_PASSWORD")"
echo "TOTP_SECRET=$(q "$TOTP_SECRET")"
other_keys "$NIKKI_DIR/bmstu.env" "$VPN_KEYS"
true
} > "$NIKKI_DIR/bmstu.env.tmp" && mv "$NIKKI_DIR/bmstu.env.tmp" "$NIKKI_DIR/bmstu.env"
fi
for f in "$KIT_DIR"/presets/*.env; do
[ -f "$PROFILES_D/${f##*/}" ] || cp "$f" "$PROFILES_D/"
done
umask 022
}
# "<id> <SUBS word>" per subscription of $SUBS (for the LuCI form)
cmd_sub_ids() {
SUBS=${SUBS:-}
sub_pairs
set -f
# shellcheck disable=SC2086
_ws=$(printf '%s ' $SUBS)
for _pr in $SUB_PAIRS; do
_w=${_ws%% *}
_ws=${_ws#"$_w"}
_ws=${_ws# }
echo "${_pr%%=*} $_w"
done
}
# Settings from the LuCI form: <env> holds BOOT_LINKS, SUBS, SUB<i>_PROXY/HWID,
# HWID_*, TORRENT, RU_IPS, OPENVPN, VPN_* (empty secrets = keep), TAILSCALE, TS_*,
# FORM=1, OVPN_CHECK_URL, TS_CHECK_URL, HY2 + HY2_<NAME>_*.
# Validates, writes common.env/bmstu.env, builds and restarts the current profile.
cmd_configure() {
[ -f "${1:-}" ] || die "usage: configure <env>"
# saved OpenVPN secrets stay unless the form sends new ones
[ -f "$NIKKI_DIR/bmstu.env" ] && . "$NIKKI_DIR/bmstu.env"
. "$1"
rm -f "$1"
BOOT=0 BOOT_LINKS=${BOOT_LINKS:-}
if [ -n "$BOOT_LINKS" ]; then
check_boot_links
BOOT=1
fi
[ -n "${SUBS:-}" ] || die "нужна хотя бы одна подписка"
if [ "$OPENVPN" = 1 ]; then
[ -f "$NIKKI_DIR/bmstu.ovpn" ] || die "OpenVPN: нет $NIKKI_DIR/bmstu.ovpn"
[ -n "${VPN_USERNAME:-}" ] && [ -n "${VPN_PASSWORD:-}" ] && [ -n "${TOTP_SECRET:-}" ] ||
die "OpenVPN: нужны логин, пароль и TOTP-секрет"
fi
write_config
log "saved $PROFILES_D/common.env"
cmd_build
if [ "$OPENVPN" = 1 ]; then
enable_otp_cron
elif grep -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null; then
sed -i '/bmstu-otp.sh check/d' /etc/crontabs/root
/etc/init.d/cron restart
log "removed bmstu-otp.sh check from cron"
fi
cur=$(uci -q get nikki.config.profile)
cur=${cur#file:}
cur=${cur%.yaml}
[ -f "$PROFILES_D/$cur.env" ] || cur=home
cmd_use "$cur"
[ "$TAILSCALE" = 1 ] && cmd_ts_login
true
}
# install only; settings in LuCI (or questions here with --cli / without LuCI)
cmd_setup() {
cmd_install
if [ "${1:-}" != --cli ] && [ -d /www/luci-static/resources ]; then
_ip=$(uci -q get network.lan.ipaddr)
_ip=${_ip%%/*}
log ""
log "Установлено. Настройка — в браузере:"
log " http://${_ip:-<роутер>}/cgi-bin/luci/admin/services/mihomo-kit"
log " (LuCI → Службы → mihomo-kit; если пункта нет — выйди и войди снова)"
log "Вопросы в терминале вместо LuCI: mihomo-kit.sh setup --cli"
return 0
fi
[ -r "$TTY_IN" ] || die "setup --cli needs a terminal (run it over ssh)"
_redo=1
if [ -f "$PROFILES_D/common.env" ]; then
yesno _redo "$PROFILES_D/common.env уже есть. Ответить на вопросы заново" n
fi
[ "$_redo" = 1 ] && wizard
cmd_build
if grep -q "^OPENVPN=1" "$PROFILES_D/common.env"; then
enable_otp_cron
echo "OTP сейчас: $(bmstu-otp.sh otp) — сверь с приложением-генератором" > "$TTY_OUT"
fi
_profiles=$(cd "$PROFILES_D" && ls *.env | sed 's/\.env$//' | grep -v '^common$' | tr '\n' ' ')
ask _start "Какой профиль включить ($_profiles)" home
cmd_use "$_start"
grep -q "^TAILSCALE=1" "$PROFILES_D/common.env" && cmd_ts_login
{
echo
echo "Готово. Дальше:"
echo " mihomo-kit.sh use street|home переключить профиль"
echo " bmstu-otp.sh off|on|status OpenVPN (одна сессия на сервере)"
grep -q "^TAILSCALE=1" "$PROFILES_D/common.env" &&
echo " mihomo-kit.sh ts-login ссылка для входа в Tailscale (если не вошёл)"
echo " mihomo-kit.sh fix после обновления пакета nikki"
} > "$TTY_OUT"
}
# kit_version <kit.tgz>: "<commit> <date>" into $KIT_DIR/VERSION. git archive
# (what the git server serves) puts the commit id into the first tar header.
kit_version() {
_sha=$(gunzip -c "$1" 2>/dev/null | head -c 1536 | tr -c 'a-z0-9=\n' '\n' |
grep '^comment=[0-9a-f]\{40\}$' | head -n 1 | cut -c9-15)
echo "${_sha:-?} $(date '+%Y-%m-%d %H:%M')" > "$KIT_DIR/VERSION"
}
# Latest commit of the KIT_URL branch (Gitea/Forgejo API). Prints lines:
# installed <sha>, latest <sha>, message <first line>, commit <url>, compare <url>
cmd_check_update() {
_repo=${KIT_URL%/archive/*}
_branch=${KIT_URL##*/archive/}
_branch=${_branch%.tar.gz}
_host=${_repo%/*/*}
_json=$(wget -q -T 10 -O - "$_host/api/v1/repos/${_repo#"$_host"/}/branches/$_branch") ||
die "no answer from $_host"
_id=$(jsonfilter -s "$_json" -e '@.commit.id') || die "unexpected answer from $_host"
_cur=$(cut -d' ' -f1 "$KIT_DIR/VERSION" 2>/dev/null)
_cur=${_cur%-dirty}
echo "installed ${_cur:-?}"
echo "latest $(echo "$_id" | cut -c1-7)"
echo "message $(jsonfilter -s "$_json" -e '@.commit.message' | head -n 1)"
echo "commit $_repo/commit/$_id"
case "$_cur" in
'' | '?') ;;
*) echo "compare $_repo/compare/$_cur...$_id" ;;
esac
}
cmd_update() {
_apply=${1:-}
tmp=$(mktemp -d)
log "downloading $KIT_URL"
wget -qO "$tmp/kit.tgz" "$KIT_URL" || die "download failed"
tar xzf "$tmp/kit.tgz" -C "$tmp" || die "bad archive"
src=$(dirname "$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1)")
[ -n "$src" ] && [ "$src" != . ] || die "no router/mihomo-kit.sh in the archive"
src=${src%/router}
for d in templates presets router luci; do
rm -rf "${KIT_DIR:?}/$d"
[ -d "$src/$d" ] && cp -r "$src/$d" "$KIT_DIR/$d"
done
kit_version "$tmp/kit.tgz"
rm -rf "$tmp"
log "kit version $(cat "$KIT_DIR/VERSION")"
# the rest runs from the new script: this one is the old version
exec sh "$KIT_DIR/router/mihomo-kit.sh" post-update $_apply
}
cmd_post_update() {
install_files
cmd_build
cur=$(uci -q get nikki.config.profile)
cur=$(basename "${cur#file:}" .yaml)
if [ "${1:-}" != --apply ]; then
log "kit updated; to apply: mihomo-kit.sh use $cur"
return 0
fi
# a new kit may pin another core version
[ "$(mihomo -v 2>/dev/null | awk '{print $3; exit}')" = "$MIHOMO_VERSION" ] || cmd_fix
[ -f "$PROFILES_OUT/$cur.yaml" ] && cmd_use "$cur"
auto_log "updated to $(cut -d' ' -f1 "$KIT_DIR/VERSION"), profile $cur restarted"
}
AUTO_CRON='0 4 * * * /usr/bin/mihomo-kit.sh auto-update'
AUTO_LOG=$NIKKI_DIR/kit/auto-update.log
# auto_log <text>: last runs for the LuCI page (and syslog)
auto_log() {
logger -t mihomo-kit "auto-update: $*" 2>/dev/null
echo "$(date '+%Y-%m-%d %H:%M') $*" >> "$AUTO_LOG"
tail -n 20 "$AUTO_LOG" > "$AUTO_LOG.tmp" && mv "$AUTO_LOG.tmp" "$AUTO_LOG"
}
# auto-update on|off: the cron line; no argument: update if the server has a newer commit
cmd_auto_update() {
case "${1:-}" in
on | off)
sed -i '/mihomo-kit.sh auto-update/d' /etc/crontabs/root 2>/dev/null
[ "$1" = on ] && echo "$AUTO_CRON" >> /etc/crontabs/root
/etc/init.d/cron restart
log "auto-update $1"
return 0
;;
esac
export PATH=/usr/sbin:/usr/bin:/sbin:/bin:$PATH
if ! _out=$(cmd_check_update 2>&1); then
auto_log "check failed: $(echo "$_out" | tail -n 1)"
return 1
fi
_cur=$(echo "$_out" | sed -n 's/^installed //p')
_new=$(echo "$_out" | sed -n 's/^latest //p')
case "$_cur" in
"$_new"*)
auto_log "up to date ($_new)"
return 0
;;
esac
auto_log "updating $_cur -> $_new"
cmd_update --apply
}
case "${1:-}" in
render) shift; cmd_render "$@" ;;
build) shift; cmd_build "$@" ;;
use) shift; cmd_use "$@" ;;
setup) shift; cmd_setup "$@" ;;
configure) shift; cmd_configure "$@" ;;
sub-ids) cmd_sub_ids ;;
update) shift; cmd_update "$@" ;;
auto-update) shift; cmd_auto_update "$@" ;;
check-update) cmd_check_update ;;
post-update) shift; cmd_post_update "$@" ;;
install) cmd_install ;;
fix) cmd_fix ;;
ts-login) shift; cmd_ts_login "$@" ;;
*) sed -n '2,29p' "$SELF" >&2; exit 2 ;;
esac