-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathjc
More file actions
executable file
·4986 lines (4525 loc) · 198 KB
/
jc
File metadata and controls
executable file
·4986 lines (4525 loc) · 198 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# shellcheck disable=SC2155 disable=SC2120 disable=SC2024 disable=SC2034
# set -x
# Constants
SCRIPT_NAME=$(basename $0)
# Tracking directories
fMainDir=$(cd "$(dirname "$(readlink -f "$0")")" || exit; pwd)
fTKFilesDir=$fMainDir/track-files
fTKCompDir=$fMainDir/completion
fTKVimColorsDir=$fMainDir/assets/vim-colors
fTKBatThemeDir=$fMainDir/assets/bat-themes
fTKFontDir=$fMainDir/assets/fonts
fTKFontConfigDir=$fMainDir/assets/fontconfig
fTKClangdConfig=$fMainDir/assets/clangd/config.yaml
fTKtemplateDir=$fMainDir/template
fTKToolsDir=$fMainDir/nv-tools
fDownloads=$HOME/Downloads
fJCPath=$fMainDir/$SCRIPT_NAME
fFirstTimeFile=$fMainDir/".has_been_invoked"
# Cursor
fTKCursorDir=$fMainDir/assets/cursor
fTKCursorLocalSettings=$fTKCursorDir/local.settings.json
fTKCursorKeybindings=$fTKCursorDir/keybindings.json
fTKCursorRemoteSettings=$fTKCursorDir/remote.settings.json
# Claude
fTKClaudeDir=$fMainDir/assets/claude
fTKClaudeCodeSettings=$fTKClaudeDir/settings.json
fTKClaudeCodeLocalSettings=$fTKClaudeDir/settings.local.json
fTKClaudeCodeMd=$fTKClaudeDir/CLAUDE.md
fTKClaudeDesktopConfig=$fTKClaudeDir/claude_desktop_config.json
fTKClaudeMcpJson=$fTKClaudeDir/.mcp.json
# Codex
fTKCodexDir=$fMainDir/assets/codex
fTKCodexConfig=$fTKCodexDir/config.toml
# Misc
fVimPlugsManagerPath=$HOME/.vim/autoload/plug.vim
fzfBinPath=$HOME/.vim/bundle/fzf/bin/fzf
fzfTabCompPath=$HOME/.vim/bundle/fzf-tab-completion/bash/fzf-bash-completion.sh # A fzf plugin: fzf-tab-completion
fBackupDir="$HOME/Public/env.bak"
fOSCategory=debian # ubuntu/debian is the default OS type
fArch=
fNoInstallTools=
fCheckTlsConn=
fCursorAction=
fClaudeAction=
fClaudeDesktopAction=
fClaudeLinkMcpJson=
fCodexAction=
# VNC server
fVncAbbrePort=9
fVncFullPort="590${fVncAbbrePort}"
fVncResolution=2060x1080
fVncServer= # 1: start VNC server; 2: kill VNC server 3: restart VNC server
fVncLockAction=
# Display Mode | gdm: start gdm3 (graphical), text: stop gdm3 (text mode)
fDisplayMode=
fLinkClangFormatPath= # Link clang-format to this path
# Update Options
appInstallUpdate= # 1: install apps and continue; 2: install apps and exit
fNVMUpdate=
fGitLfsUpdate=
fClangdUpdate=
fDockerUpdate=
fWiresharkUpdate=
fFirefoxUpdate=
fChinesePinyinUpdate=
fXrayUpdate=
fXrayRemove=
fXrayPort=
fXrayServer=
fWireguardUpdate=
fWireguardRemove=
fWireguardPort=
fWireguardServer=
fWireguardClientName=
fSwapReq=
# RTSP Stream Playback
fRtspFlag=
fRtspMulti=
fRtspKill=
fRtspList=
fRtspFilter=
fRtspSrvIp=192.168.10.240
fRtspStream=
MAX_RTSP_STREAMS=10
fRtspScreenRes= # Exp: 4k Mi Monitor resolution 3360 x 1890
fSambaServerFlag= # 1: Start samba server 2: Start samba server and reset password
# Camera ACL (OpenWrt firewall rules Block_C700_NN)
fGwHost="root@192.168.10.1"
fGwPort=8822
fGwAclAction="" # block | unblock | status
fGwAclTarget="" # c700_01 | c700_02 | all
# SSH Tunnel (autossh port forward over VPN)
# Remote host: the real server autossh connects to. Not derivable from the
# sing-box config because sing-box only sees 127.0.0.1 in xray-tunnel mode.
fSshTunnelRemoteIp=10.6.10.221
# Ports are populated from .outbounds[proxy].server_port when xray-tunnel
# mode is detected in launchSingbox; unused in other modes.
fSshTunnelRemotePort=""
fSshTunnelLocalPort=""
fSshTunnelAutosshPid=""
# Singbox (sing-box proxy)
fSingbox=
fSingboxConfig="$HOME/Documents/sing-box-config.jsonc"
fSingboxLink="" # xray | wireguard — which config to symlink
fSingboxProxyMode="" # wireguard | xray-direct | xray-tunnel
fSingboxRetryTimeout=180 # seconds to retry after VPN/tunnel drop
fSingboxMonitorPid=""
fSingboxCleaning=0
fSingboxRecoveryMarker=""
# Colors
RED='\033[31m'
GREEN='\033[32m'
MAGENTA='\033[35m'
LIGHTYELLOW='\033[93m'
BOLD='\033[1m'
NORMAL='\033[0m'
BLUE='\033[34m'
GREY='\033[90m'
CYAN='\033[36m'
RESET='\033[0m'
COLOR=$MAGENTA
# On macOS, always initialize Homebrew environment
if [[ $(uname -s) == 'Darwin' ]]; then
[ -x /opt/homebrew/bin/brew ] && eval "$(/opt/homebrew/bin/brew shellenv)"
[ -x /usr/local/bin/brew ] && eval "$(/usr/local/bin/brew shellenv)"
fi
usage() {
cat << _EOF
Usage: $SCRIPT_NAME [OPTIONS]
Set up coding environment, manage VNC/Samba servers, and play RTSP camera streams.
Common Options:
-h, --help Print this help message
-n, --no-tools Don't install tools
-d, --debug Enable debug mode
--check-tls Check TLS connection
--link-clang-format Link clang-format to current path
--auto-remove Remove unused packages
--update Update all packages
--upgrade Upgrade all packages
Update Options (installed by default on first run):
--nvm Update NVM
--git-lfs Update Git LFS from PackageCloud
--apps Update Apps
--chinese-pinyin Update Rime Pinyin
--docker Update Docker from Docker PPA
--wireshark Update Wireshark from Wireshark PPA
--firefox Update Firefox from Mozilla PPA
--clangd Update Clangd from Github
Cursor Options:
--cursor-backup Back up Cursor local, remote, and keybinding JSON files
--cursor-restore Restore Cursor local, remote, and keybinding JSON files
Samba Options:
--samba Install and configure Samba Server
--samba-reset-password Reset Samba Server password
Swap Options:
--swap Add swap file (default 8G)
Vnc Server Options:
--vnc,--vnc-start Start VNC server
--vnc-stop Stop VNC server
--vnc-restart Restart VNC server
Display Mode Options:
--gdm Switch to graphical mode (start gdm3)
--text Switch to text mode (stop gdm3)
Vnc Lock Options:
--vnclock Effect options: [unlock|lock|status]
--unlock-vnc Unlock VNC, equivalent to --vnclock unlock
--lock-vnc Lock VNC, equivalent to --vnclock lock
RTSP Options:
--rtsp Play RTSP stream with mpv (low-latency)
--rtsp-all Play multiple RTSP streams in tiled layout
--rtsp-kill Kill all running mpv instances
--rtsp-list List all available streams from go2rtc
--rtsp-raw Play all *_raw streams in tiled layout
--rtsp-h264 Play all *_h264 streams in tiled layout
--rtsp-stream <stream> Specify stream name (default: first from go2rtc)
--rtsp-ip <ip> Specify RTSP server IP (default: ${fRtspSrvIp})
--rtsp-resolution <WxH> Set screen resolution for tiling (e.g. 3360x1890)
Camera ACL Options (controls Block_C700_NN rules on OpenWrt router):
--acl-block <c700_01|c700_02|all> Enable block rule(s) — camera(s) offline
--acl-unblock <c700_01|c700_02|all> Disable block rule(s) — camera(s) online
--acl-status <c700_01|c700_02|all> Show current rule state
Singbox Options:
--singbox Launch sing-box proxy (auto-detects xray or WireGuard)
--singbox-xray Link xray sing-box config to ~/Documents
--singbox-wg Link WireGuard sing-box config to ~/Documents
Xray Options (server-side only — run on the Xray server host):
--xray Install or update Xray from Github
--xray-port <port> Set Xray listen port (default: 443)
--xray-server <ip> Set server IP in share URL (auto-detected if omitted)
--xray-remove Remove Xray from system
WireGuard Options (server-side only — run on the WireGuard server host):
--wg Install/configure WireGuard VPN server
--wg-port <port> Set WireGuard listen port (default: 51820)
--wg-server <ip> Set server IP in client config (auto-detected if omitted)
--wg-client <name> Set client config name (default: client1)
--wg-remove Remove WireGuard from system
Claude Options:
--claude Install or upgrade Claude Code (CLI)
--claude-remove Remove Claude Code
--claude-backup Back up Claude Code CLI settings
(settings.json, settings.local.json, CLAUDE.md)
--claude-restore Restore Claude Code CLI settings
--claude-link-mcp Symlink tracked .mcp.json into current directory
--claude-desktop-backup Back up macOS Claude Desktop config
(claude_desktop_config.json)
--claude-desktop-restore Restore macOS Claude Desktop config
Codex Options:
--codex Install or upgrade Codex (CLI)
--codex-remove Remove Codex
--codex-backup Back up Codex CLI settings
(config.toml)
--codex-restore Restore Codex CLI settings
Gemini Options:
--gemini Install or upgrade Gemini (CLI)
--gemini-remove Remove Gemini CLI
Examples:
$SCRIPT_NAME -h
$SCRIPT_NAME --link-clang-format \$HOME/crosslv
_EOF
exit 0
}
# Detect and use GNU getopt if available (required for long options on macOS)
GETOPT_BIN="getopt"
if command -v /opt/homebrew/opt/gnu-getopt/bin/getopt &> /dev/null; then
GETOPT_BIN="/opt/homebrew/opt/gnu-getopt/bin/getopt"
elif command -v /usr/local/opt/gnu-getopt/bin/getopt &> /dev/null; then
GETOPT_BIN="/usr/local/opt/gnu-getopt/bin/getopt"
fi
SHORTOPTS="hdnf"
# Two colons: The option takes an optional argument
LONGOPTS="help,debug,no-tools,clangd,docker,link-clang-format::,auto-remove,nvm\
upgrade,chinese-pinyin,apps,apps-only,vnc-restart,vnc-stop,unlock-vnc,vnclock:,\
lock-vnc,vnc-start,vnc,firefox,update,samba,samba-reset-password,wireshark,\
git-lfs,rtsp,rtsp-all,rtsp-kill,rtsp-list,rtsp-raw,rtsp-h264,rtsp-stream:,\
rtsp-ip:,rtsp-resolution:,check-tls::,swap::,gdm,text,claude,claude-remove,\
claude-backup,claude-restore,claude-desktop-backup,claude-desktop-restore,claude-link-mcp,\
codex,codex-remove,codex-backup,codex-restore,\
gemini,gemini-remove,cursor-backup,cursor-restore,\
singbox,singbox-xray,singbox-wg,\
xray,xray-port:,xray-server:,xray-remove,wg,wg-port:,wg-server:,wg-client:,wg-remove,\
acl-block:,acl-unblock:,acl-status:"
# Use getopt to parse command-line options
if ! PARSED=$("$GETOPT_BIN" --options $SHORTOPTS --longoptions "$LONGOPTS" --name "$0" -- "$@"); then
echo -e "${COLOR}Error: Failed to parse command-line options.${RESET}" >&2
echo -e "${CYAN}Tip: On macOS, install GNU getopt: ${GREY}brew install gnu-getopt${RESET}" >&2
exit 1
fi
# Reset positional parameters to the parsed values
eval set -- "$PARSED"
checkNodeEnv() {
local nvmSh="$HOME/.nvm/nvm.sh"
if [ ! -s "$nvmSh" ]; then
echo -e "${LIGHTYELLOW}NVM not found. Installing NVM and Node.js first...${RESET}"
local nvmVersion="v0.40.3"
if ! curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/"$nvmVersion"/install.sh | bash; then
echo -e "${RED}Error: Failed to install NVM.${RESET}"
return 1
fi
fi
if [ -s "$nvmSh" ]; then
export NVM_DIR="$HOME/.nvm"
# shellcheck source=/dev/null
source "$nvmSh"
else
echo -e "${RED}Error: nvm.sh not found.${RESET}"
return 1
fi
if ! command -v node &>/dev/null; then
echo -e "${LIGHTYELLOW}Node.js not found. Installing latest LTS via NVM...${RESET}"
nvm install --lts
nvm alias default lts/*
fi
}
installClaude() {
local bin ver
echo -e "${BOLD}${COLOR}Installing Claude Code${RESET}"
# Use npm on every OS. Homebrew's claude-code cask is auto-bumped from
# the GCS bucket and routinely lags npm by 10+ patch releases, so even
# macOS users get fresher binaries from the npm package (which ships
# native binaries per platform via optionalDependencies).
checkNodeEnv || return 1
echo -e " ${LIGHTYELLOW}Installing ${BLUE}@anthropic-ai/claude-code${RESET}${GREY}...${RESET}"
npm install -g @anthropic-ai/claude-code @anthropic-ai/sandbox-runtime || {
echo -e " ${RED}Error: npm install failed.${RESET}" >&2
return 1
}
hash -r
ver=$(claude -v 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
bin=$(command -v claude 2>/dev/null || echo 'not found')
bin=${bin/#$HOME/\~}
echo -e "${GREEN}✔ Installed${RESET} ${GREY}v${ver:-unknown}${RESET}"
echo -e "${GREEN}✔${RESET} ${GREY}Binary${RESET}: ${CYAN}${bin}${RESET}"
echo -e "${GREEN}✔${RESET} ${GREY}Config${RESET}: ${CYAN}~/.claude${RESET}"
}
installCodex() {
local bin ver
echo -e "${BOLD}${COLOR}Installing Codex${RESET}"
# See installClaude — npm is the canonical, most up-to-date channel
# on every OS.
checkNodeEnv || return 1
echo -e " ${LIGHTYELLOW}Installing ${BLUE}@openai/codex${RESET}${GREY}...${RESET}"
npm install -g @openai/codex || {
echo -e " ${RED}Error: npm install failed.${RESET}" >&2
return 1
}
hash -r
ver=$(codex --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
bin=$(command -v codex 2>/dev/null || echo 'not found')
bin=${bin/#$HOME/\~}
echo -e "${GREEN}✔ Installed${RESET} ${GREY}v${ver:-unknown}${RESET}"
echo -e "${GREEN}✔${RESET} ${GREY}Binary${RESET}: ${CYAN}${bin}${RESET}"
echo -e "${GREEN}✔${RESET} ${GREY}Config${RESET}: ${CYAN}~/.codex${RESET}"
}
removeClaude() {
echo -e "${BOLD}${COLOR}Removing Claude Code${RESET}"
if [ -s "$HOME/.nvm/nvm.sh" ]; then
export NVM_DIR="$HOME/.nvm"
# shellcheck source=/dev/null
source "$NVM_DIR/nvm.sh"
fi
local removed=false
local pkg
for pkg in @anthropic-ai/claude-code @anthropic-ai/sandbox-runtime; do
if command -v npm &>/dev/null && npm list -g "$pkg" &>/dev/null; then
echo -e " ${LIGHTYELLOW}Removing ${BLUE}${pkg}${RESET}${GREY}...${RESET}"
npm uninstall -g "$pkg"
removed=true
fi
done
# Clean up legacy macOS Homebrew installs from earlier versions of jc.
if [[ $(uname -s) == 'Darwin' ]] && command -v brew &>/dev/null \
&& brew list --cask claude-code &>/dev/null; then
echo -e " ${LIGHTYELLOW}Removing legacy ${BLUE}claude-code${RESET} ${GREY}cask...${RESET}"
brew uninstall --cask claude-code
removed=true
fi
if ! $removed; then
echo -e " ${GREY}Claude Code is not installed.${RESET}"
return 0
fi
echo -e "${GREEN}✔${GREY} Claude Code removed.${RESET}"
}
removeCodex() {
echo -e "${BOLD}${COLOR}Removing Codex${RESET}"
if [ -s "$HOME/.nvm/nvm.sh" ]; then
export NVM_DIR="$HOME/.nvm"
# shellcheck source=/dev/null
source "$NVM_DIR/nvm.sh"
fi
local removed=false
if command -v npm &>/dev/null && npm list -g @openai/codex &>/dev/null; then
echo -e " ${LIGHTYELLOW}Removing ${BLUE}@openai/codex${RESET}${GREY}...${RESET}"
npm uninstall -g @openai/codex
removed=true
fi
# Clean up legacy macOS Homebrew installs from earlier versions of jc.
if [[ $(uname -s) == 'Darwin' ]] && command -v brew &>/dev/null \
&& brew list --cask codex &>/dev/null; then
echo -e " ${LIGHTYELLOW}Removing legacy ${BLUE}codex${RESET} ${GREY}cask...${RESET}"
brew uninstall --cask codex
removed=true
fi
if ! $removed; then
echo -e " ${GREY}Codex is not installed.${RESET}"
return 0
fi
echo -e "${GREEN}✔${GREY} Codex removed.${RESET}"
}
installGemini() {
local bin ver
echo -e "${BOLD}${COLOR}Installing Gemini CLI${RESET}"
# Same npm channel as claude/codex — Google ships gemini-cli only via
# @google/gemini-cli on npm; no Homebrew or system package today.
checkNodeEnv || return 1
echo -e " ${LIGHTYELLOW}Installing ${BLUE}@google/gemini-cli${RESET}${GREY}...${RESET}"
npm install -g @google/gemini-cli || {
echo -e " ${RED}Error: npm install failed.${RESET}" >&2
return 1
}
hash -r
ver=$(gemini --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
bin=$(command -v gemini 2>/dev/null || echo 'not found')
bin=${bin/#$HOME/\~}
echo -e "${GREEN}✔ Installed${RESET} ${GREY}v${ver:-unknown}${RESET}"
echo -e "${GREEN}✔${RESET} ${GREY}Binary${RESET}: ${CYAN}${bin}${RESET}"
echo -e "${GREEN}✔${RESET} ${GREY}Config${RESET}: ${CYAN}~/.gemini${RESET}"
}
removeGemini() {
echo -e "${BOLD}${COLOR}Removing Gemini CLI${RESET}"
if [ -s "$HOME/.nvm/nvm.sh" ]; then
export NVM_DIR="$HOME/.nvm"
# shellcheck source=/dev/null
source "$NVM_DIR/nvm.sh"
fi
local removed=false
if command -v npm &>/dev/null && npm list -g @google/gemini-cli &>/dev/null; then
echo -e " ${LIGHTYELLOW}Removing ${BLUE}@google/gemini-cli${RESET}${GREY}...${RESET}"
npm uninstall -g @google/gemini-cli
removed=true
fi
if ! $removed; then
echo -e " ${GREY}Gemini CLI is not installed.${RESET}"
return 0
fi
echo -e "${GREEN}✔${GREY} Gemini CLI removed.${RESET}"
}
gwAclControl() {
local action="$1" target="$2"
local rules="" desired=""
case "$target" in
c700_01) rules="Block_C700_01" ;;
c700_02) rules="Block_C700_02" ;;
all) rules="Block_C700_01 Block_C700_02" ;;
*)
echo -e "${RED}Error: Invalid target '$target'. Valid: c700_01, c700_02, all${RESET}" >&2
return 2
;;
esac
case "$action" in
block) desired="1" ;;
unblock) desired="0" ;;
status) desired="" ;;
esac
local rc=0 remote_env
printf -v remote_env "DESIRED='%s' RULES='%s' sh -s" "$desired" "$rules"
ssh -p "$fGwPort" -o ConnectTimeout=5 -o BatchMode=yes \
"$fGwHost" "$remote_env" <<'REMOTE' || rc=$?
set -e
missing=0
changed=0
for n in $RULES; do
sec=$(uci show firewall | awk -F'[.=]' -v n="$n" '
tolower($0) ~ "\\.name=\x27" tolower(n) "\x27" { print $2; exit }
')
if [ -z "$sec" ]; then
echo "ERROR: firewall rule $n not found" >&2
missing=1
continue
fi
cur=$(uci -q get firewall.$sec.enabled); [ -z "$cur" ] && cur=1
if [ -z "$DESIRED" ]; then
echo "$n: enabled=$cur (section=$sec)"
continue
fi
if [ "$cur" != "$DESIRED" ]; then
uci set firewall.$sec.enabled="$DESIRED"; changed=1
echo "$n: $cur -> $DESIRED"
else
echo "$n: already $DESIRED"
fi
done
if [ "$missing" = 1 ]; then
echo "ERROR: one or more rules not found; aborting without commit" >&2
exit 3
fi
if [ "$changed" = 1 ]; then
uci commit firewall
/etc/init.d/firewall reload >/dev/null 2>&1
echo "firewall reloaded"
fi
REMOTE
if [ "$rc" -eq 3 ]; then
echo -e "${LIGHTYELLOW}Hint: verify rule names with:${RESET}"
echo -e " ssh -p $fGwPort $fGwHost \"uci show firewall | grep -i '\\.name='\"" >&2
fi
return "$rc"
}
while true; do
case "$1" in
-n|--no-tools)
fNoInstallTools=true
shift
;;
--apps)
appInstallUpdate=1
shift
;;
--apps-only)
appInstallUpdate=2
shift
;;
--nvm)
fNVMUpdate=true
shift
;;
--git-lfs)
fGitLfsUpdate=true
shift
;;
--docker)
fDockerUpdate=true
shift
;;
--wireshark)
fWiresharkUpdate=true
shift
;;
--firefox)
fFirefoxUpdate=true
shift
;;
--clangd)
fClangdUpdate=true
shift
;;
--rtsp)
fRtspFlag=1
shift
;;
--rtsp-all)
fRtspFlag=1
fRtspMulti=1
shift
;;
--rtsp-kill)
fRtspKill=1
shift
;;
--rtsp-list)
fRtspList=1
shift
;;
--rtsp-raw)
fRtspFlag=1
fRtspMulti=1
fRtspFilter="_raw"
shift
;;
--rtsp-h264)
fRtspFlag=1
fRtspMulti=1
fRtspFilter="_h264"
shift
;;
--rtsp-stream)
fRtspFlag=1
fRtspStream="$2"
shift 2
;;
--rtsp-ip)
fRtspSrvIp="$2"
shift 2
;;
--rtsp-resolution)
fRtspScreenRes="${2//x/ }"
shift 2
;;
--samba)
fSambaServerFlag=1
shift
;;
--samba-reset-password)
fSambaServerFlag=2
shift
;;
--vnc|--vnc-start)
fVncServer=1
shift
;;
--vnc-stop)
fVncServer=2
shift
;;
--vnc-restart)
fVncServer=3
shift
;;
--vnclock)
fVncLockAction="$2"
shift 2
;;
--unlock-vnc)
fVncLockAction="unlock"
shift
;;
--lock-vnc)
fVncLockAction="lock"
shift
;;
--gdm)
fDisplayMode="gdm"
shift
;;
--text)
fDisplayMode="text"
shift
;;
--chinese-pinyin)
fChinesePinyinUpdate=true
shift
;;
--swap)
fSwapReq=true
shift 2
;;
--link-clang-format)
# $1 is '--link-clang-format'.
# $2 is always an empty string '', even if an argument is provided.
# Any provided argument appears sequentially in the positional parameters.
# Example: $ jc huhu --link-clang-format /home/user1/ leetcode
# => jc --link-clang-format '' -- 'huhu' '/home/user1/' 'leetcode'
# CRITICAL: Always 'shift 2' to consume the option ($1) and the
# empty placeholder token ($2).
fLinkClangFormatPath="$PWD"
shift 2
;;
--check-tls)
fCheckTlsConn=true
shift 2
;;
--auto-remove)
echo -e "${COLOR}Removing unused packages${RESET}"
sudo apt autoremove -y
shift
exit 0
;;
--update)
echo -e "${COLOR}Updating all packages${RESET}"
if [[ $(uname -s) == 'Darwin' ]]; then
brew update
else
sudo apt update -y
fi
shift
exit 0
;;
--upgrade)
echo -e "${COLOR}Updating all packages${RESET}"
if [[ $(uname -s) == 'Darwin' ]]; then
brew update
echo -e "${COLOR}Upgrading all packages${RESET}"
brew upgrade
else
sudo apt update -y
echo -e "${COLOR}Upgrading all packages${RESET}"
sudo apt upgrade -y --allow-downgrades
fi
# Upgrade globally installed npm packages
nvmSh="$HOME/.nvm/nvm.sh"
if [ -s "$nvmSh" ]; then
# shellcheck source=/dev/null
source "$nvmSh"
# Parse `npm list -g --depth=0` lines like `├── @scope/pkg@1.2.3`
# or `└── pkg@1.2.3` and emit just the package name. Avoid grep
# -oP / \K / lookahead — BSD grep on macOS lacks PCRE.
globalPkgs=$(npm list -g --depth=0 2>/dev/null | awk '/── / {
pkg = $NF
n = split(pkg, parts, "@")
if (n == 2) print parts[1]
else if (n == 3 && parts[1] == "") print "@" parts[2]
}')
if [ -n "$globalPkgs" ]; then
echo -e "${COLOR}Upgrading globally installed npm packages${RESET}"
for pkg in $globalPkgs; do
echo -e " ${LIGHTYELLOW}Upgrading ${BLUE}$pkg${RESET}"
npm install -g "${pkg}@latest"
done
fi
fi
shift
exit 0
;;
--claude)
installClaude
shift
exit 0
;;
--claude-remove)
removeClaude
shift
exit 0
;;
--claude-backup)
fClaudeAction="backup"
shift
;;
--claude-restore)
fClaudeAction="restore"
shift
;;
--claude-desktop-backup)
fClaudeDesktopAction="backup"
shift
;;
--claude-desktop-restore)
fClaudeDesktopAction="restore"
shift
;;
--claude-link-mcp)
fClaudeLinkMcpJson=1
shift
;;
--codex)
installCodex
shift
exit 0
;;
--codex-remove)
removeCodex
shift
exit 0
;;
--codex-backup)
fCodexAction="backup"
shift
;;
--codex-restore)
fCodexAction="restore"
shift
;;
--gemini)
installGemini
shift
exit 0
;;
--gemini-remove)
removeGemini
shift
exit 0
;;
--xray)
fXrayUpdate=true
shift
;;
--xray-port)
fXrayPort="$2"
if ! [[ "$fXrayPort" =~ ^[0-9]+$ ]] || (( fXrayPort < 1 || fXrayPort > 65535 )); then
echo -e "${RED}Error: Invalid Xray port: $fXrayPort${RESET}"
exit 1
fi
shift 2
;;
--xray-server)
fXrayServer="$2"
shift 2
;;
--xray-remove)
fXrayRemove=true
shift
;;
--wg)
fWireguardUpdate=true
shift
;;
--wg-port)
fWireguardPort="$2"
if ! [[ "$fWireguardPort" =~ ^[0-9]+$ ]] || (( fWireguardPort < 1 || fWireguardPort > 65535 )); then
echo -e "${RED}Error: Invalid WireGuard port: $fWireguardPort${RESET}"
exit 1
fi
shift 2
;;
--wg-server)
fWireguardServer="$2"
shift 2
;;
--wg-client)
fWireguardClientName="$2"
shift 2
;;
--wg-remove)
fWireguardRemove=true
shift
;;
--cursor-backup)
fCursorAction="backup"
shift
;;
--cursor-restore)
fCursorAction="restore"
shift
;;
--singbox)
fSingbox=1
shift
;;
--singbox-xray)
fSingboxLink="xray"
shift
;;
--singbox-wg)
fSingboxLink="wireguard"
shift
;;
--acl-block)
fGwAclAction="block"
fGwAclTarget="$2"
shift 2
;;
--acl-unblock)
fGwAclAction="unblock"
fGwAclTarget="$2"
shift 2
;;
--acl-status)
fGwAclAction="status"
fGwAclTarget="$2"
shift 2
;;
-d|--debug)
set -x
echo -e "${COLOR}Debug mode enabled${RESET}"
shift
;;
-h|--help)
usage
;;
--)
shift
break
;;
*)
echo -e "${RED}Error: Invalid option: $1${RESET}" >&2
exit 1
;;
esac
done
if [ -n "$fGwAclAction" ]; then
gwAclControl "$fGwAclAction" "$fGwAclTarget" || exit $?
exit 0
fi
checkSudoPrivilege() {
echo -e "${COLOR}Checking Sudo Privilege${RESET}"
if sudo -n true 2>/dev/null; then
echo -e "${GREEN}✔${GREY} User has passwordless sudo access.${RESET}"
return
fi
if [[ $(uname -s) == 'Linux' ]]; then
local sudoersFile="/etc/sudoers.d/$USER"
# if id -nG "$USER" | grep -qw "sudo"; then
if sudo -v; then
echo -e "${LIGHTYELLOW}User $USER has sudo but requires a password. Configuring passwordless sudo${RESET}"
echo "$USER ALL=(ALL) NOPASSWD:ALL" | sudo tee "$sudoersFile" > /dev/null
sudo chmod 0440 "$sudoersFile"
else
echo -e "${RED}✗${GREY} User $USER has no sudo privilege.${RESET}"
echo -e "${LIGHTYELLOW}Granting sudo access via root account (root password required)${RESET}"
su -c "usermod -aG sudo $USER && echo '$USER ALL=(ALL) NOPASSWD:ALL' > $sudoersFile && chmod 0440 $sudoersFile" root
fi
if sudo -n true 2>/dev/null; then
echo -e "${GREEN}✔${GREY} Passwordless sudo access configured for $USER.${RESET}"
return
fi
fi
echo -e "${RED}✗${GREY} Failed to obtain passwordless sudo access. Please configure manually.${RESET}"
exit 1
}
checkTlsConnection() {
local targetHost=${1:-"github.com"}
if command -v openssl &> /dev/null; then
checkTlsConnWithOpenssl "$targetHost"
elif command -v curl &> /dev/null; then
checkTlsConnWithCurl "$targetHost"
else
echo -e "${LIGHTYELLOW}curl and openssl are not installed. Aborting.${RESET}"
exit 1
fi
}
checkTlsConnWithOpenssl() {
local targetHost=${1:-"github.com"}
echo -e "${COLOR}Verifying server certificate against CA list for: ${NORMAL}${targetHost}${RESET}"
# Use openssl s_client to connect and verify the certificate.
# -connect <host>:<port>
# -servername <host> for SNI
# -showcerts (optional, but useful if debugging; we'll focus on the verify return code)
# -verify_return_error: Crucial for getting a meaningful exit code on verification failure.
# </dev/null: Prevents blocking on stdin.
# 2>&1: Captures both stdout and stderr.
local opensslOutput
opensslOutput=$(openssl s_client -connect "${targetHost}:443" -servername "${targetHost}" -verify_return_error </dev/null 2>&1)
local opensslExitCode=$?
# openssl s_client returns non-zero for many errors, including verification failures.
# A successful verification usually results in 'verify return:1'.
# We need to check the exit code *and* the output for 'verify return:1'.
# Grep for the specific success indicator and check the exit code.
# The 'verify return:1' is the most direct confirmation of CA trust.
# Note: openssl s_client may return non-zero even on successful verification due to connection closure
if echo "$opensslOutput" | grep -q 'verify return:1' && ! echo "$opensslOutput" | grep -q 'verify return:0'; then
echo -e "${GREEN}✔${GREY} Server certificate is trusted (legally issued and verifiable against CA list).${RESET}"
# Optionally display specific certificate details if needed for context:
local certDetails=$(echo "$opensslOutput" | openssl x509 -noout -subject -issuer -dates)
if [ -n "$certDetails" ]; then
echo -e "${CYAN}--- Certificate Details ---${RESET}"
echo "$certDetails"
echo -e "${CYAN}---------------------------${RESET}"
fi
else
# Handle failures
echo -e "${RED}✗${GREY} Server certificate is NOT trusted or an error occurred.${RESET}"
if echo "$opensslOutput" | grep -q 'verify return:.*error'; then
echo -e "${RED} Reason: Certificate validation failed.${RESET}"
elif echo "$opensslOutput" | grep -q 'connect:errno='; then
echo -e "${RED} Reason: Could not connect to the server.${RESET}"
elif echo "$opensslOutput" | grep -q 'certificate verify failed'; then
echo -e "${RED} Reason: OpenSSL reported a certificate verification failure.${RESET}"
else
echo -e "${RED} Reason: Unknown error or non-verified certificate.${RESET}"
fi
# Show a snippet of the output for debugging
echo -e "${CYAN}☞ ${GREY}openssl output snippet:${RESET}"
echo "$opensslOutput" | head -n 10
exit 1 # Exit on any failure
fi
}
checkTlsConnWithCurl() {
local targetHost=${1:-"github.com"}
echo -e "${COLOR}Checking TLS Certificate Trust for: ${NORMAL}${targetHost}${RESET}"
local curlOutput
# -fsS = --fail --silent --show-error
curlOutput=$(curl --head -fsS --connect-timeout 5 "https://${targetHost}" 2>&1)
local curlExitCode=$?
# Exit code 60 is specifically for peer certificate verification failure.
if [ $curlExitCode -eq 0 ]; then
echo -e "${GREEN}✔${GREY} TLS connection successful. Certificate is trusted.${RESET}"
elif [ $curlExitCode -eq 60 ]; then
echo -e "${RED}✗${GREY} TLS connection failed: Certificate validation error.${RESET}"
echo -e "${RED} This is often due to a corporate proxy (Man-in-the-Middle).${RESET}"