master bs
 1#!/bin/sh
 2
 3[ -d /etc/sing-box/list ] || { echo "please mkdir /etc/sing-box/list/"; exit 1; }
 4
 5serviceNm="sing-box"
 6
 7m=0
 8for f in /etc/sing-box/list/*.json; do
 9	[ -f "$f" ] || continue
10	n=$(basename "$f" .json)
11	[ ${#n} -gt $m ] && m=${#n}
12done
13
14case "$1" in
15	-L|--list)
16		i=1
17		for f in /etc/sing-box/list/*.json; do
18			[ -f "$f" ] || continue
19			n=$(basename "$f" .json)
20			p=$(jq -r '.outbounds[] | select(.type != "direct") | .type' "$f")
21			[ -z "$p" ] && p="unknown"
22			printf "%-*s [%d] [%s]\n" "$m" "$n" "$i" "$p"
23			i=$((i + 1))
24		done
25		;;
26	-C|--current)
27		if [ -L /etc/sing-box/config.json ] && [ -e /etc/sing-box/config.json ]; then
28			l=$(readlink /etc/sing-box/config.json)
29			n=$(basename "$l" .json)
30			p=$(jq -r '.outbounds[] | select(.type != "direct") | .type' "$l")
31			[ -z "$p" ] && p="unknown"
32			i=1
33			for f in /etc/sing-box/list/*.json; do
34				if [ -f "$f" ] && [ "$(basename "$f" .json)" = "$n" ]; then
35					printf "%-*s [%d] [%s]\n" "$m" "$n" "$i" "$p"
36					break
37				fi
38				i=$((i + 1))
39			done
40		else
41			echo "no active config"
42		fi
43		;;
44	-S|--stop)
45		if [ "$(id -u)" -ne 0 ]; then
46			echo "run as root"
47			exit 1
48		fi
49		rc-service "$serviceNm" stop
50		rm -f /etc/sing-box/config.json
51		;;
52	-*)
53		echo "invalid option $1"
54		exit 1
55		;;
56	*)
57		if [ -z "$1" ]; then
58			echo "rtfm"
59			echo "> man bs"
60			exit 1
61		fi
62
63		if [ "$1" -eq "$1" ] 2>/dev/null; then
64			if [ "$(id -u)" -ne 0 ]; then
65				echo "run as root"
66				exit 1
67			fi
68			i=1
69			for f in /etc/sing-box/list/*.json; do
70				[ -f "$f" ] || continue
71				if [ "$i" -eq "$1" ]; then
72					ln -sf "/etc/sing-box/list/$(basename "$f")" /etc/sing-box/config.json
73					rc-service "$serviceNm" restart
74					exit 0
75				fi
76				i=$((i + 1))
77			done
78			echo "index $1 not found"
79			exit 1
80		fi
81
82		if [ ! -f "/etc/sing-box/list/$1.json" ]; then
83			echo "config $1 not found"
84			exit 1
85		fi
86
87		ln -sf "/etc/sing-box/list/$1.json" /etc/sing-box/config.json
88		rc-service "$serviceNm" restart
89		;;
90esac