-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinstall.sh
More file actions
1854 lines (1683 loc) · 67.4 KB
/
Copy pathinstall.sh
File metadata and controls
1854 lines (1683 loc) · 67.4 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
#!/bin/bash
# ============================================================================
# SMART Sniffer Agent — Unified Installer (Linux + macOS)
#
# One-liner install:
# curl -sSL https://raw.githubusercontent.com/DAB-LABS/smart-sniffer/main/install.sh | sudo bash
#
# Or pin a specific version:
# VERSION=0.1.0 curl -sSL ... | sudo bash
#
# Uninstall:
# curl -sSL https://raw.githubusercontent.com/DAB-LABS/smart-sniffer/main/install.sh | sudo UNINSTALL=1 bash
# (or if already downloaded: sudo bash install.sh --uninstall)
#
# What this script does:
# 1. Detects OS (Linux/macOS) and architecture (amd64/arm64)
# 2. Downloads the correct binary from the latest GitHub Release
# 3. Verifies the download against SHA256 checksums
# 4. Installs smartmontools if missing
# 5. Prompts for port, token, and scan interval
# 6. Installs the binary, config, and system service
# 7. Starts the agent and verifies it's running
# ============================================================================
set -e
REPO="DAB-LABS/smart-sniffer"
BINARY_NAME="smartha-agent"
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m'; BOLD='\033[1m'; NC='\033[0m'
info() { echo -e "${BOLD} --> $*${NC}"; }
success() { echo -e "${GREEN} ✓ $*${NC}"; }
warn() { echo -e "${YELLOW} ⚠ $*${NC}"; }
fail() { echo -e "${RED} ✗ $*${NC}"; exit 1; }
# ---------------------------------------------------------------------------
# Disk usage picker — detects real block-device mounts, shows numbered list,
# user enters comma-separated numbers, "all", or "none".
# Sets FS_YAML with the config.yaml entries and FS_DISPLAY with mount list.
# ---------------------------------------------------------------------------
FS_YAML=""
FS_DISPLAY=""
# Unescape kernel-style mountinfo path escapes (\040 \011 \012 \134).
# Per fs/proc_namespace.c the kernel escapes space, tab, newline, and
# backslash in path fields. Decoder must process \134 (backslash)
# LAST so that literal backslashes do not re-trigger other rules.
# Implementation: route \134 through a sentinel that cannot collide
# with valid path content, decode the other three, then resolve the
# sentinel to a real backslash.
unescape_mountinfo_path() {
local s="$1"
s="${s//\\134/__SMARTSNIFFER_BS__}"
s="${s//\\040/ }"
s="${s//\\011/ }"
# Newline replacement uses ANSI-C $'...' for the literal newline char.
s="${s//\\012/$'\n'}"
s="${s//__SMARTSNIFFER_BS__/\\}"
printf '%s' "$s"
}
# Phase 2: btrfs picker display fallback.
#
# `df` returns total=0 for btrfs in some contexts (kernel statvfs
# undercount on multi-device btrfs / specific kernel versions). Shell
# out to `btrfs filesystem usage --raw <mp>` for accurate values.
#
# Output on stdout (success): "<total>\t<used>" as raw bytes.
# Output on failure (any reason): empty stdout, non-zero exit.
#
# Failure causes (all caller-visible): btrfs binary missing, subprocess
# timed out (5s), or output couldn't be parsed. Caller distinguishes
# "btrfs binary missing" via the cached BTRFS_BIN var, so this helper
# stays simple.
btrfs_usage_for() {
local mp="$1"
local out total used
if command -v timeout >/dev/null 2>&1; then
out=$(timeout 5s btrfs filesystem usage --raw "$mp" 2>/dev/null) || return 1
else
out=$(btrfs filesystem usage --raw "$mp" 2>/dev/null) || return 1
fi
# Match the leading "Device size:" line (in the Overall: block).
total=$(echo "$out" | awk '/^[[:space:]]*Device size:/ {print $3; exit}')
# Match the bare "Used:" line in Overall: -- NOT the per-block-group
# "Used:" fields that appear inline like "Data,single: Size:N, Used:N".
used=$(echo "$out" | awk '/^[[:space:]]*Used:[[:space:]]+[0-9]+[[:space:]]*$/ {print $2; exit}')
[ -z "$total" ] || [ -z "$used" ] && return 1
[[ ! "$total" =~ ^[0-9]+$ ]] && return 1
[[ ! "$used" =~ ^[0-9]+$ ]] && return 1
printf '%s\t%s\n' "$total" "$used"
}
pick_filesystems() {
FS_YAML=""
FS_DISPLAY=""
# Parallel arrays for detected filesystems.
local -a fs_mps=()
local -a fs_devs=()
local -a fs_types=()
local -a fs_roots=()
local -a fs_uuids=()
local -a fs_labels=()
# ---------------------------------------------------------------
# Source selection: mountinfo on Linux (Phase 1B-1), mount on macOS.
#
# /proc/self/mountinfo gives us the `root` field, which lets us
# dedup bind mounts via the strict (source, fstype, root) key.
# /proc/mounts lacks `root`, so it cannot tell duplicate mounts
# of the same filesystem apart from bind mounts of subdirs.
#
# Fallback chain on Linux:
# 1. /proc/self/mountinfo (preferred -- enables dedup)
# 2. /proc/mounts (fallback -- duplicates may slip through)
# 3. mount (last resort, parses mount-output format)
# ---------------------------------------------------------------
local mounts mount_source=""
if [[ "$OSTYPE" == darwin* ]]; then
mounts=$(mount)
mount_source="mount"
elif [ -r /proc/self/mountinfo ]; then
mounts=$(cat /proc/self/mountinfo)
mount_source="mountinfo"
elif [ -f /proc/mounts ]; then
mounts=$(cat /proc/mounts)
mount_source="proc_mounts"
else
mounts=$(mount)
mount_source="mount"
fi
# Phase 2: cache btrfs binary availability once. Used by the per-mount
# fallback when df returns zero on btrfs filesystems. We track whether
# any btrfs mount was encountered so we can warn the user once if the
# binary is missing -- one warning per picker run, not per entry.
local btrfs_bin=""
command -v btrfs >/dev/null 2>&1 && btrfs_bin=$(command -v btrfs)
local btrfs_seen_missing_progs=0
while IFS= read -r line; do
local dev mp fstype root="/"
# macOS mount output: /dev/disk3s1s1 on / (apfs, sealed, local, ...)
# Linux /proc/self/mountinfo:
# 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
# ^id par maj ^root ^mp ^opts opt-fields - ^fstype ^source super-opts
# Linux /proc/mounts: /dev/sda1 / ext4 rw,relatime 0 0
if [[ "$OSTYPE" == darwin* ]]; then
dev=$(echo "$line" | awk '{print $1}')
mp=$(echo "$line" | sed 's/.* on \(.*\) (.*/\1/' | sed 's/ *$//')
fstype=$(echo "$line" | sed 's/.*(\([^,)]*\).*/\1/' | sed 's/ *$//')
elif [ "$mount_source" = "mountinfo" ]; then
# mountinfo: fields before `-` separator vary in count (optional
# fields). Split on " - " first, then extract.
# Pre-`-`: 1=id 2=parent 3=major:minor 4=root 5=mp 6=opts ...
# Post-`-`: fstype source super_opts
local pre post
pre="${line% - *}"
post="${line#* - }"
# Skip if separator not found (malformed line).
[ "$pre" = "$line" ] && continue
root=$(echo "$pre" | awk '{print $4}')
mp=$(echo "$pre" | awk '{print $5}')
fstype=$(echo "$post" | awk '{print $1}')
dev=$(echo "$post" | awk '{print $2}')
# Phase 1B-2: unescape kernel path escapes. Apply to mp, root,
# and dev. fstype never contains escapes per kernel, but the
# path fields routinely do (any whitespace in mount paths or
# device names becomes \040, etc).
mp="$(unescape_mountinfo_path "$mp")"
root="$(unescape_mountinfo_path "$root")"
dev="$(unescape_mountinfo_path "$dev")"
else
dev=$(echo "$line" | awk '{print $1}')
mp=$(echo "$line" | awk '{print $2}')
fstype=$(echo "$line" | awk '{print $3}')
# /proc/mounts lacks `root`. Default to "/" so dedup degrades
# to (dev, fstype) -- correct for partition mounts, may
# collapse subdir bind mounts incorrectly. Best effort fallback.
root="/"
# /proc/mounts uses the same kernel escape rules as mountinfo,
# so unescape paths and source here too.
mp="$(unescape_mountinfo_path "$mp")"
dev="$(unescape_mountinfo_path "$dev")"
fi
# Filter to real block devices and common filesystems.
case "$dev" in
/dev/sd*|/dev/nvme*|/dev/md*|/dev/mapper/*|/dev/vd*|/dev/xvd*|/dev/hd*|/dev/disk*) ;;
*) case "$fstype" in zfs) ;; *) continue ;; esac ;;
esac
# Skip virtual/special filesystems.
case "$fstype" in
tmpfs|overlay|squashfs|proc|sysfs|devtmpfs|devpts|cgroup*|autofs|fusectl|securityfs|debugfs|configfs|pstore|binfmt_misc)
continue ;;
esac
# Skip macOS system/virtual volumes and pseudo-filesystems.
if [[ "$OSTYPE" == darwin* ]]; then
case "$mp" in
/System/Volumes/Preboot|/System/Volumes/Recovery|/System/Volumes/VM)
continue ;;
/System/Volumes/xarts|/System/Volumes/iSCPreboot|/System/Volumes/Hardware)
continue ;;
esac
case "$fstype" in devfs|autofs|synthfs) continue ;; esac
fi
# Skip snap and docker mounts.
case "$mp" in /snap/*|/var/lib/docker/*) continue ;; esac
# Get usage info from df.
# macOS df doesn't support -B1 (GNU coreutils). Use -k for 1K blocks
# on macOS and -B1 for byte-accurate values on Linux.
local df_line total pct hr_total used
if [[ "$OSTYPE" == darwin* ]]; then
df_line=$(df -k "$mp" 2>/dev/null | tail -1)
total=$(echo "$df_line" | awk '{print $2}')
# df -k returns 1K blocks; convert to bytes.
total=$((total * 1024))
pct=$(echo "$df_line" | awk '{print $5}' | tr -d '%')
else
df_line=$(df -B1 "$mp" 2>/dev/null | tail -1)
total=$(echo "$df_line" | awk '{print $2}')
pct=$(echo "$df_line" | awk '{print $5}' | tr -d '%')
fi
# Phase 2: btrfs display fallback. df returns zero for btrfs in some
# picker contexts (statvfs vs multi-device). Re-fetch via
# `btrfs filesystem usage --raw`. Two failure modes both fall through
# to "(unknown size)": btrfs-progs missing, or parse failure.
if [ "$fstype" = "btrfs" ] && { [ -z "$total" ] || [ "$total" = "0" ]; }; then
if [ -n "$btrfs_bin" ]; then
local btrfs_out
if btrfs_out=$(btrfs_usage_for "$mp"); then
total=$(echo "$btrfs_out" | awk '{print $1}')
used=$(echo "$btrfs_out" | awk '{print $2}')
if [ "$total" -gt 0 ] 2>/dev/null; then
pct=$(awk -v u="$used" -v t="$total" 'BEGIN { printf "%d", (u*100)/t }')
fi
fi
else
# No btrfs binary available. Fall through to (unknown size).
btrfs_seen_missing_progs=1
fi
fi
if [ -z "$total" ] || [ "$total" = "0" ]; then
hr_total="?"
pct="?"
elif [ "$total" -gt 1099511627776 ] 2>/dev/null; then
hr_total="$(echo "$total" | awk '{printf "%.1fT", $1/1099511627776}')";
elif [ "$total" -gt 1073741824 ] 2>/dev/null; then
hr_total="$(echo "$total" | awk '{printf "%.0fG", $1/1073741824}')";
elif [ "$total" -gt 1048576 ] 2>/dev/null; then
hr_total="$(echo "$total" | awk '{printf "%.0fM", $1/1048576}')";
else
hr_total="${total}B"
fi
# When size is unknown, swap the formatted label for an explicit
# "(unknown size)" so the user doesn't see "? (?% used)".
local fs_label
if [ "$hr_total" = "?" ]; then
fs_label="$(printf '%-16s %-6s %s' "$mp" "$fstype" "(unknown size)")"
else
fs_label="$(printf '%-16s %-6s %6s (%s%% used)' "$mp" "$fstype" "$hr_total" "$pct")"
fi
# Get UUID.
local uuid=""
if command -v blkid &>/dev/null && [ -b "$dev" ]; then
uuid=$(blkid -s UUID -o value "$dev" 2>/dev/null || true)
fi
if [ -z "$uuid" ] && command -v diskutil &>/dev/null; then
uuid=$(diskutil info "$dev" 2>/dev/null | grep "Volume UUID" | awk '{print $NF}' || true)
fi
fs_mps+=("$mp")
fs_devs+=("$dev")
fs_types+=("$fstype")
fs_roots+=("$root")
fs_uuids+=("$uuid")
fs_labels+=("$fs_label")
done <<< "$mounts"
# Phase 2: warn once if we encountered btrfs mounts and the binary is
# missing. This makes the (unknown size) labels self-explanatory --
# the user knows what to install if they want real numbers.
if [ "$btrfs_seen_missing_progs" = "1" ]; then
warn "btrfs-progs not installed -- btrfs entries will show (unknown size). Install btrfs-progs to enable size detection."
fi
# ---------------------------------------------------------------
# Phase 1B-1: Strict (source, fstype, root) dedup.
#
# Two mounts sharing this composite key are guaranteed to point at
# the same filesystem subtree (per kernel mountinfo semantics).
# Tiebreak: keep the entry with the shortest mount_point.
#
# NOTE on filter scope: the dev filter above only admits /dev/* and
# zfs entries. fuse.rclone, fuse.sshfs, and similar FUSE backends
# are dropped before reaching dedup. Widening the filter to surface
# those mounts is a separate scope decision -- see follow-up note
# in docs/internal/research/filesystem-reporting-edge-cases.md.
# ---------------------------------------------------------------
if [ "$mount_source" = "mountinfo" ] && [ "${BASH_VERSINFO[0]:-0}" -ge 4 ] && [ "${#fs_mps[@]}" -gt 0 ]; then
# Associative arrays (local -A) require bash 4+. On older bash (QNAP QTS
# ships 3.2), skip dedup -- the user may see duplicate bind mounts in the
# picker but everything still works.
local -a dd_mps=() dd_devs=() dd_types=() dd_roots=() dd_uuids=() dd_labels=()
local -A seen_key=() # key -> index into dd_* arrays
local i key existing_idx existing_mp
for ((i=0; i<${#fs_mps[@]}; i++)); do
key="${fs_devs[$i]}|${fs_types[$i]}|${fs_roots[$i]}"
if [ -z "${seen_key[$key]:-}" ]; then
# First occurrence -- append.
dd_mps+=("${fs_mps[$i]}")
dd_devs+=("${fs_devs[$i]}")
dd_types+=("${fs_types[$i]}")
dd_roots+=("${fs_roots[$i]}")
dd_uuids+=("${fs_uuids[$i]}")
dd_labels+=("${fs_labels[$i]}")
seen_key[$key]=$((${#dd_mps[@]} - 1))
else
# Duplicate -- replace existing if this mount_point is shorter.
existing_idx="${seen_key[$key]}"
existing_mp="${dd_mps[$existing_idx]}"
if [ "${#fs_mps[$i]}" -lt "${#existing_mp}" ]; then
dd_mps[$existing_idx]="${fs_mps[$i]}"
# Other fields are equal by construction (same dedup key);
# only the label needs refreshing because it embeds mp.
dd_labels[$existing_idx]="${fs_labels[$i]}"
fi
fi
done
fs_mps=("${dd_mps[@]}")
fs_devs=("${dd_devs[@]}")
fs_types=("${dd_types[@]}")
fs_roots=("${dd_roots[@]}")
fs_uuids=("${dd_uuids[@]}")
fs_labels=("${dd_labels[@]}")
fi
local count=${#fs_mps[@]}
if [ "$count" -eq 0 ]; then
info "No block-device filesystems detected — skipping disk usage monitoring."
return
fi
# ---------------------------------------------------------------
# Phase 1B-3: canonical entry + bind-mount hiding.
#
# Bind mounts are a Linux kernel feature exposed via mountinfo.
# On non-Linux platforms (macOS, BSD) there are no bind mounts to
# group, so every entry is canonical. The grouping logic uses bash
# 4+ associative arrays (local -A) which are not available on
# macOS's bash 3.2, so we gate the entire block on mount_source.
#
# Group dedup'd entries by (source, fstype). Within each group:
# - If any entry has root="/", canonical = shortest mp among
# those root="/" entries. All other entries (root="/" non-shortest
# plus any root != "/") are hidden by default.
# - If no entry has root="/" (typical for btrfs subvolumes), no
# hiding -- every entry is its own real subtree.
#
# Single-entry groups: no hiding, no tag, no count.
# ---------------------------------------------------------------
local -a is_canonical=() is_hidden=() hidden_count_for=()
local total_hidden=0
local groups_with_hidden=0
local i grp
if [ "$mount_source" = "mountinfo" ] && [ "${BASH_VERSINFO[0]:-0}" -ge 4 ]; then
# Linux: full bind-mount grouping with associative arrays (bash 4+).
# Skipped on bash 3.2 (QNAP QTS) -- falls through to the else branch
# where every entry is treated as canonical (no hiding).
local -A group_canonical=() # group_key -> canonical idx
local -A group_has_root_slash=() # group_key -> "1" if any root="/" exists
local -A group_hidden_count=() # group_key -> N
# Initialize flag arrays.
for ((i=0; i<count; i++)); do
is_canonical+=("0")
is_hidden+=("0")
hidden_count_for+=("0")
done
# Pass 1: detect which (source, fstype) groups have a root="/" entry.
for ((i=0; i<count; i++)); do
grp="${fs_devs[$i]}|${fs_types[$i]}"
if [ "${fs_roots[$i]}" = "/" ]; then
group_has_root_slash[$grp]="1"
fi
done
# Pass 2: pick canonical per group.
# With root="/": shortest mp among entries where root="/".
# Without root="/": every entry is its own canonical (subvolume case).
for ((i=0; i<count; i++)); do
grp="${fs_devs[$i]}|${fs_types[$i]}"
if [ "${group_has_root_slash[$grp]:-}" = "1" ]; then
# Group has a root="/" entry. Only consider root="/" candidates.
[ "${fs_roots[$i]}" != "/" ] && continue
if [ -z "${group_canonical[$grp]:-}" ]; then
group_canonical[$grp]="$i"
else
local cur="${group_canonical[$grp]}"
if [ "${#fs_mps[$i]}" -lt "${#fs_mps[$cur]}" ]; then
group_canonical[$grp]="$i"
fi
fi
else
# No root="/" in group -- every entry is canonical.
is_canonical[$i]="1"
fi
done
# Pass 3: mark canonicals from group_canonical map; mark non-canonicals
# in root="/"-bearing groups as hidden.
for grp in "${!group_canonical[@]}"; do
local cidx="${group_canonical[$grp]}"
is_canonical[$cidx]="1"
done
for ((i=0; i<count; i++)); do
grp="${fs_devs[$i]}|${fs_types[$i]}"
if [ "${group_has_root_slash[$grp]:-}" = "1" ] && [ "${is_canonical[$i]}" = "0" ]; then
is_hidden[$i]="1"
group_hidden_count[$grp]=$((${group_hidden_count[$grp]:-0} + 1))
fi
done
# Annotate canonicals with their group's hidden count for display.
for grp in "${!group_hidden_count[@]}"; do
local n="${group_hidden_count[$grp]}"
[ "$n" -ge 1 ] && groups_with_hidden=$((groups_with_hidden + 1))
total_hidden=$((total_hidden + n))
local cidx="${group_canonical[$grp]}"
hidden_count_for[$cidx]="$n"
done
else
# Non-Linux (macOS, BSD): no bind mounts. Every entry is canonical.
for ((i=0; i<count; i++)); do
is_canonical+=("1")
is_hidden+=("0")
hidden_count_for+=("0")
done
fi
# ---------------------------------------------------------------
# Display: default (collapsed) view shows only canonicals, with a
# [+N bind mounts hidden] tag when applicable. If the user types y
# to expand, reprint with all entries; non-canonical ones get a
# [bind mount] tag.
# ---------------------------------------------------------------
local expanded=0
local -a visible_indices=()
build_visible_indices() {
visible_indices=()
for ((i=0; i<count; i++)); do
if [ "$expanded" = "1" ] || [ "${is_hidden[$i]}" = "0" ]; then
visible_indices+=("$i")
fi
done
}
print_visible() {
echo ""
echo -e " ${BOLD}Disk Usage Monitoring${NC}"
echo " Select mountpoints to report to Home Assistant."
echo ""
local pos idx label suffix n plural
for ((pos=0; pos<${#visible_indices[@]}; pos++)); do
idx="${visible_indices[$pos]}"
label="${fs_labels[$idx]}"
suffix=""
if [ "$expanded" = "1" ]; then
# Expanded view: tag non-canonical entries.
[ "${is_canonical[$idx]}" = "0" ] && suffix=" [bind mount]"
else
# Collapsed view: tag canonicals that have hidden siblings.
n="${hidden_count_for[$idx]}"
if [ "$n" -ge 1 ]; then
plural="s"
[ "$n" -eq 1 ] && plural=""
suffix=" [+${n} bind mount${plural} hidden]"
fi
fi
echo " $((pos + 1))) ${label}${suffix}"
done
echo ""
}
build_visible_indices
print_visible
# Show the y/N expansion prompt only if there are hidden mounts
# AND we are still in collapsed view.
if [ "$expanded" = "0" ] && [ "$total_hidden" -ge 1 ]; then
local entry_word="entries"
[ "$total_hidden" -eq 1 ] && entry_word="entry"
local part_word="partitions"
[ "$groups_with_hidden" -eq 1 ] && part_word="partition"
local hide_msg="${total_hidden} bind-mount ${entry_word} hidden across ${groups_with_hidden} ${part_word}."
echo " ${hide_msg}"
read -rp " Show all entries? (y/N) [N]: " EXPAND_CHOICE < "$TTY_IN"
case "${EXPAND_CHOICE:-N}" in
y|Y|yes|YES)
expanded=1
build_visible_indices
print_visible
;;
esac
fi
local visible_count=${#visible_indices[@]}
local range_hint="1"
[ "$visible_count" -gt 1 ] && range_hint="1,2..${visible_count}"
read -rp " Monitor ($range_hint / all / none) [all]: " FS_CHOICE < "$TTY_IN"
FS_CHOICE="${FS_CHOICE:-all}"
# Parse selection. `num` refers to position within visible_indices.
local -a selected_indices=()
case "$FS_CHOICE" in
all|ALL|a|A)
for ((pos=0; pos<visible_count; pos++)); do
selected_indices+=("${visible_indices[$pos]}")
done
;;
none|NONE|n|N)
info "Disk usage monitoring disabled."
return
;;
*)
# Comma-separated numbers.
IFS=',' read -ra nums <<< "$FS_CHOICE"
for num in "${nums[@]}"; do
num=$(echo "$num" | tr -d ' ')
if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le "$visible_count" ]; then
selected_indices+=("${visible_indices[$((num - 1))]}")
else
warn "Skipping invalid choice: $num"
fi
done
;;
esac
if [ ${#selected_indices[@]} -eq 0 ]; then
info "No valid mountpoints selected — disk usage monitoring disabled."
return
fi
# Build YAML and display string.
FS_YAML="filesystems:"
local -a display_mps=()
for idx in "${selected_indices[@]}"; do
FS_YAML="${FS_YAML}
- path: \"${fs_mps[$idx]}\"
uuid: \"${fs_uuids[$idx]}\"
device: \"${fs_devs[$idx]}\"
fstype: \"${fs_types[$idx]}\""
display_mps+=("${fs_mps[$idx]}")
done
FS_DISPLAY=$(IFS=', '; echo "${display_mps[*]}")
success "Monitoring ${#selected_indices[@]} mountpoint(s): $FS_DISPLAY"
}
# ---------------------------------------------------------------------------
# Drive picker — shows drives detected by smartctl, enriched with lsblk
# metadata. Auto-excludes iSCSI/FC/unknown transports (yellow).
# Sets EXCLUDE_YAML with config entries and EXCLUDE_DISPLAY with paths.
# ---------------------------------------------------------------------------
pick_drives() {
EXCLUDE_YAML=""
EXCLUDE_DISPLAY=""
# macOS: skip the drive picker. lsblk doesn't exist so transport detection
# is blind (everything shows "unknown"/yellow). macOS doesn't expose iSCSI
# LUNs as block devices the way Linux does -- this picker targets Linux
# servers (Proxmox, TrueNAS, Synology, etc.).
if [[ "$OSTYPE" == darwin* ]]; then
return
fi
# Need smartctl to enumerate drives.
if ! command -v smartctl &>/dev/null; then
return
fi
local scan_json
scan_json=$(smartctl --json --scan 2>/dev/null || true)
if [ -z "$scan_json" ]; then
return
fi
# Extract device paths from smartctl --scan JSON.
local -a dev_paths=()
while IFS= read -r p; do
[ -n "$p" ] && dev_paths+=("$p")
done < <(echo "$scan_json" | grep -o '"name"[[:space:]]*:[[:space:]]*"[^"]*"' | sed 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)"/\1/')
if [ "${#dev_paths[@]}" -eq 0 ]; then
return
fi
# Build lsblk lookup table (Linux only): dev -> "SIZE MODEL TRAN VENDOR"
local -a dev_size=()
local -a dev_model=()
local -a dev_tran=()
local -a dev_vendor=()
local -a dev_byid=()
local has_lsblk="false"
if command -v lsblk &>/dev/null; then
has_lsblk="true"
local lsblk_out
# Use -P (pairs) for unambiguous key="value" output. Eliminates all
# column-alignment issues when MODEL has spaces or VENDOR/TRAN is empty.
lsblk_out=$(lsblk -P -o NAME,SIZE,MODEL,TRAN,VENDOR --nodeps --noheadings 2>/dev/null || true)
fi
for i in "${!dev_paths[@]}"; do
local dpath="${dev_paths[$i]}"
local dname
dname=$(basename "$dpath")
# Defaults
dev_size[$i]=""
dev_model[$i]=""
dev_tran[$i]="unknown"
dev_vendor[$i]=""
dev_byid[$i]=""
# Enrich from lsblk if available.
if [ "$has_lsblk" = "true" ] && [ -n "$lsblk_out" ]; then
local lsblk_line
# Match by NAME="dname" in the pairs output.
lsblk_line=$(echo "$lsblk_out" | grep -m1 "NAME=\"$dname\"" || true)
# NVMe: smartctl returns controller path (/dev/nvme0) but lsblk uses
# namespace path (nvme0n1). Fall back to ${name}n1 if exact match fails.
if [ -z "$lsblk_line" ] && [[ "$dname" == nvme* ]]; then
lsblk_line=$(echo "$lsblk_out" | grep -m1 "NAME=\"${dname}n1\"" || true)
fi
if [ -n "$lsblk_line" ]; then
# Extract fields from key="value" pairs. Handles spaces in MODEL, empty VENDOR, etc.
dev_size[$i]=$(echo "$lsblk_line" | sed -n 's/.*SIZE="\([^"]*\)".*/\1/p')
dev_model[$i]=$(echo "$lsblk_line" | sed -n 's/.*MODEL="\([^"]*\)".*/\1/p')
dev_vendor[$i]=$(echo "$lsblk_line" | sed -n 's/.*VENDOR="\([^"]*\)".*/\1/p')
local tran_val
tran_val=$(echo "$lsblk_line" | sed -n 's/.*TRAN="\([^"]*\)".*/\1/p')
if [ -n "$tran_val" ]; then
dev_tran[$i]="$tran_val"
fi
fi
fi
# Try to find a stable by-id path.
if [ -d "/dev/disk/by-id" ]; then
local byid_path
byid_path=$(find /dev/disk/by-id -maxdepth 1 -lname "*/$dname" ! -name 'wwn-*' 2>/dev/null | head -1)
if [ -n "$byid_path" ]; then
dev_byid[$i]="$byid_path"
fi
fi
done
local count="${#dev_paths[@]}"
if [ "$count" -eq 0 ]; then
return
fi
# Determine which drives are "yellow" (pre-excluded).
local -a is_yellow=()
local -a default_selected=()
local default_nums=""
for i in "${!dev_paths[@]}"; do
local tran="${dev_tran[$i]}"
if [ "$tran" = "iscsi" ] || [ "$tran" = "fc" ] || [ "$tran" = "unknown" ]; then
is_yellow[$i]="1"
else
is_yellow[$i]="0"
default_selected+=("$((i + 1))")
fi
done
default_nums=$(IFS=','; echo "${default_selected[*]}")
# Display the picker.
echo ""
echo -e " ${BOLD}Drive Scanner${NC}"
echo " Select which drives to monitor with SMART Sniffer."
echo ""
for i in "${!dev_paths[@]}"; do
local num="$((i + 1))"
local dpath="${dev_paths[$i]}"
local size="${dev_size[$i]}"
local model="${dev_model[$i]}"
local tran="${dev_tran[$i]}"
# Build display line: " 1) /dev/sda 119.2G LITEONIT LMT-128M6M [sata]"
local label
label=$(printf "%-14s %6s %-30s [%s]" "$dpath" "$size" "$model" "$tran")
if [ "${is_yellow[$i]}" = "1" ]; then
echo -e " ${num}) ${YELLOW}${label}${NC}"
else
echo -e " ${num}) ${GREEN}${label}${NC}"
fi
done
echo ""
# Only show yellow explanation if there are yellow drives.
local has_yellow="false"
for i in "${!dev_paths[@]}"; do
if [ "${is_yellow[$i]}" = "1" ]; then
has_yellow="true"
break
fi
done
if [ "$has_yellow" = "true" ]; then
echo " Yellow drives use network storage or unknown transport and may not"
echo " support SMART. They are excluded from the default selection."
echo ""
fi
local range_hint="1"
[ "$count" -gt 1 ] && range_hint="1,2..${count}"
read -rp " Monitor (${range_hint} / all / none) [${default_nums}]: " DRIVE_CHOICE < "$TTY_IN"
DRIVE_CHOICE="${DRIVE_CHOICE:-$default_nums}"
# Parse selection.
local -a selected_nums=()
case "$DRIVE_CHOICE" in
all|ALL|a|A)
for ((i=0; i<count; i++)); do
selected_nums+=("$((i + 1))")
done
;;
none|NONE|n|N)
# Exclude everything -- unusual but valid.
;;
*)
IFS=',' read -ra nums <<< "$DRIVE_CHOICE"
for num in "${nums[@]}"; do
num=$(echo "$num" | tr -d ' ')
if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le "$count" ]; then
selected_nums+=("$num")
else
warn "Skipping invalid choice: $num"
fi
done
;;
esac
# Build exclude list: anything NOT selected is excluded.
local -a exclude_paths=()
for i in "${!dev_paths[@]}"; do
local num="$((i + 1))"
local is_selected="false"
for sel in "${selected_nums[@]}"; do
if [ "$sel" = "$num" ]; then
is_selected="true"
break
fi
done
if [ "$is_selected" = "false" ]; then
# Prefer by-id path for stability.
if [ -n "${dev_byid[$i]}" ]; then
exclude_paths+=("${dev_byid[$i]}")
else
exclude_paths+=("${dev_paths[$i]}")
fi
fi
done
if [ "${#exclude_paths[@]}" -eq 0 ]; then
info "All drives selected -- no exclusions."
return
fi
# Warn if every drive is excluded (VM, no local drives, etc.).
if [ "${#exclude_paths[@]}" -eq "${#dev_paths[@]}" ]; then
echo ""
warn "No drives selected for SMART monitoring."
echo " The agent will still run (disk usage, mDNS) but won't report drive health."
read -rp " Continue? [Y/n]: " _confirm < "$TTY_IN"
_confirm="${_confirm:-y}"
if [ "$_confirm" != "y" ] && [ "$_confirm" != "Y" ]; then
info "Re-run the installer to change drive selection."
EXCLUDE_YAML=""
EXCLUDE_DISPLAY=""
return
fi
fi
# Build YAML output.
EXCLUDE_YAML="exclude_devices:"
for ep in "${exclude_paths[@]}"; do
EXCLUDE_YAML="${EXCLUDE_YAML}
- \"${ep}\""
done
EXCLUDE_DISPLAY=$(IFS=', '; echo "${exclude_paths[*]}")
_pick_drives_total="$count"
success "Excluding ${#exclude_paths[@]} device(s): $EXCLUDE_DISPLAY"
}
# ---------------------------------------------------------------------------
# Network interface picker — shows numbered list, user enters a number
# or "all". Sets ADV_IFACE to the chosen interface or "" for auto-filter.
# ---------------------------------------------------------------------------
# Cosmetic labels for the interface picker UI. This list does NOT need to
# mirror every entry in agent/config.go's defaultSkipPrefixes (51 entries).
# It only tags common virtual interfaces so users can identify them during
# install. The actual runtime filtering is handled by the Go agent.
# Keep loosely in sync -- add entries when users report confusion.
VIRTUAL_PREFIXES="docker|docker_gwbridge|br-|lxcbr|lxdbr|veth|podman|hassio|zt|tailscale|ts|wg|tun|tap|utun|virbr|vmbr|fwbr|fwpr|fwln|vbox|vmnet|lo"
pick_interface() {
local -a iface_names=()
local -a iface_labels=()
IFACE_COUNT=0
NON_VIRTUAL_COUNT=0
for iface in $(ls /sys/class/net 2>/dev/null || ifconfig -l 2>/dev/null | tr ' ' '\n'); do
local ip4=""
if command -v ip &>/dev/null; then
ip4=$(ip -4 addr show "$iface" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}' | head -1)
else
ip4=$(ifconfig "$iface" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}' | head -1)
fi
[ -z "$ip4" ] && continue
IFACE_COUNT=$((IFACE_COUNT + 1))
local tag_label=""
if echo "$iface" | grep -qiE "^($VIRTUAL_PREFIXES)"; then
case "$iface" in
docker*|br-*) tag_label="${YELLOW}(Docker)${NC}" ;;
veth*|podman*) tag_label="${YELLOW}(container)${NC}" ;;
lxcbr*|lxdbr*) tag_label="${YELLOW}(LXC/LXD)${NC}" ;;
hassio*) tag_label="${YELLOW}(HA OS)${NC}" ;;
zt*) tag_label="${YELLOW}(ZeroTier)${NC}" ;;
tailscale*|ts*) tag_label="${YELLOW}(Tailscale)${NC}" ;;
wg*) tag_label="${YELLOW}(WireGuard)${NC}" ;;
tun*|tap*|utun*) tag_label="${YELLOW}(VPN tunnel)${NC}" ;;
virbr*) tag_label="${YELLOW}(libvirt)${NC}" ;;
vmbr*|fwbr*|fwpr*|fwln*) tag_label="${YELLOW}(Proxmox)${NC}" ;;
vbox*) tag_label="${YELLOW}(VirtualBox)${NC}" ;;
vmnet*) tag_label="${YELLOW}(VMware)${NC}" ;;
lo*) tag_label="${YELLOW}(loopback)${NC}" ;;
*) tag_label="${YELLOW}(virtual)${NC}" ;;
esac
else
NON_VIRTUAL_COUNT=$((NON_VIRTUAL_COUNT + 1))
fi
iface_names+=("$iface")
iface_labels+=("$(printf '%-16s %s %s' "$iface" "$ip4" "$tag_label")")
done
ADV_IFACE=""
if [ "$IFACE_COUNT" -le 1 ]; then
info "Single interface detected — using auto-filter."
return
fi
echo ""
echo -e " ${BOLD}Network Interface (mDNS)${NC}"
echo " Home Assistant uses this to auto-discover the agent."
echo ""
for ((i=0; i<${#iface_names[@]}; i++)); do
echo -e " $((i + 1))) ${iface_labels[$i]}"
done
echo ""
read -rp " Advertise on (1-${#iface_names[@]} / all) [all]: " IFACE_CHOICE < "$TTY_IN"
IFACE_CHOICE="${IFACE_CHOICE:-all}"
case "$IFACE_CHOICE" in
all|ALL|a|A|"")
info "mDNS: auto-filter mode (all physical interfaces)."
ADV_IFACE=""
;;
*)
if [[ "$IFACE_CHOICE" =~ ^[0-9]+$ ]] && [ "$IFACE_CHOICE" -ge 1 ] && [ "$IFACE_CHOICE" -le "${#iface_names[@]}" ]; then
ADV_IFACE="${iface_names[$((IFACE_CHOICE - 1))]}"
success "mDNS will advertise on: $ADV_IFACE"
else
warn "Invalid choice — using auto-filter."
ADV_IFACE=""
fi
;;
esac
}
# Returns the count of non-virtual interfaces (call after pick_interface or
# after running the same detection loop). Used to decide whether to prompt
# during upgrades from pre-interface-picker configs.
count_non_virtual_interfaces() {
NON_VIRTUAL_COUNT=0
for iface in $(ls /sys/class/net 2>/dev/null || ifconfig -l 2>/dev/null | tr ' ' '\n'); do
if command -v ip &>/dev/null; then
ip4=$(ip -4 addr show "$iface" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}' | head -1)
else
ip4=$(ifconfig "$iface" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}' | head -1)
fi
[ -z "$ip4" ] && continue
if ! echo "$iface" | grep -qiE "^($VIRTUAL_PREFIXES)"; then
NON_VIRTUAL_COUNT=$((NON_VIRTUAL_COUNT + 1))
fi
done
}
# ---------------------------------------------------------------------------
# Install-path defaults (may be overridden by resolve_install_paths below)
# ---------------------------------------------------------------------------
INSTALL_BIN="/usr/local/bin/$BINARY_NAME"
INSTALL_CFG="/etc/smartha-agent"
# ---------------------------------------------------------------------------
# Resolve writable install paths
#
# Standard Linux/macOS: /usr/local/bin + /etc/smartha-agent
# Immutable-rootfs (ZimaOS, etc.): /DATA/smartha-agent (bin + config)
# Generic fallback: /opt/smartha-agent (bin + config)
#
# The probe runs as root (installer requires sudo), so a writability failure
# genuinely means the filesystem is read-only, not a permissions issue.
# ---------------------------------------------------------------------------
resolve_install_paths() {
# Candidate 1: standard paths (works on most Linux, macOS, Proxmox, etc.)
if mkdir -p /usr/local/bin 2>/dev/null && [ -w /usr/local/bin ]; then
INSTALL_BIN="/usr/local/bin/$BINARY_NAME"
INSTALL_CFG="/etc/smartha-agent"
return
fi
# Candidate 2: /DATA (ZimaOS, CasaOS, and similar NAS distros)
if [ -d /DATA ] && mkdir -p /DATA/smartha-agent 2>/dev/null && [ -w /DATA/smartha-agent ]; then
INSTALL_BIN="/DATA/smartha-agent/$BINARY_NAME"
INSTALL_CFG="/DATA/smartha-agent"
warn "Immutable root filesystem detected — installing to /DATA/smartha-agent/"
return
fi
# Candidate 3: /opt (generic fallback)
if mkdir -p /opt/smartha-agent 2>/dev/null && [ -w /opt/smartha-agent ]; then
INSTALL_BIN="/opt/smartha-agent/$BINARY_NAME"
INSTALL_CFG="/opt/smartha-agent"
warn "Standard paths not writable — installing to /opt/smartha-agent/"
return
fi
fail "No writable install location found. Tried /usr/local/bin, /DATA/smartha-agent, /opt/smartha-agent."
}
# ---------------------------------------------------------------------------
# Uninstall
# ---------------------------------------------------------------------------
do_uninstall() {
echo ""
echo -e "${BOLD}╔══════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║ SMART Sniffer Agent — Uninstaller ║${NC}"
echo -e "${BOLD}╚══════════════════════════════════════════╝${NC}"
echo ""
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
# Stop and remove service
if [ "$OS" = "linux" ]; then
# systemd service
if systemctl is-active --quiet smartha-agent 2>/dev/null; then
info "Stopping systemd service..."
systemctl stop smartha-agent
fi
if [ -f /etc/systemd/system/smartha-agent.service ]; then
info "Removing systemd service..."
systemctl disable smartha-agent 2>/dev/null || true
rm -f /etc/systemd/system/smartha-agent.service
systemctl daemon-reload
success "systemd service removed."
fi
# init.d service (QNAP, non-systemd Linux)
if [ -f /etc/init.d/smartha-agent ]; then
info "Stopping init.d service..."
/etc/init.d/smartha-agent stop 2>/dev/null || true
if command -v update-rc.d >/dev/null 2>&1; then
update-rc.d -f smartha-agent remove 2>/dev/null || true
elif command -v rc-update >/dev/null 2>&1; then