-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·3739 lines (3308 loc) · 113 KB
/
install.sh
File metadata and controls
executable file
·3739 lines (3308 loc) · 113 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
set -euo pipefail
umask 022
shopt -s lastpipe 2>/dev/null || true
# Ultimate Bug Scanner - Installation Script
# https://github.com/Dicklesworthstone/ultimate_bug_scanner
# Always present latest main version to users; actual binary will be fetched
# from main branch (not releases). VERSION is cosmetic only.
VERSION_DEFAULT="main"
# Handle case when script is piped (BASH_SOURCE[0] not set)
if [[ -n "${BASH_SOURCE[0]:-}" ]]; then
VERSION_FILE="$(cd -- "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)/VERSION"
VERSION="$(cat "$VERSION_FILE" 2>/dev/null || echo "$VERSION_DEFAULT")"
else
VERSION="$VERSION_DEFAULT"
fi
SCRIPT_NAME="ubs"
INSTALL_NAME="ubs"
REPO_URL="https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master"
ARTIFACT_BASE_DEFAULT="https://github.com/Dicklesworthstone/ultimate_bug_scanner/releases/download/v${VERSION}"
ARTIFACT_BASE="${UBS_ARTIFACT_BASE:-$ARTIFACT_BASE_DEFAULT}"
MINISIGN_PUBKEY="${UBS_MINISIGN_PUBKEY:-}" # Set to minisign public key line (untrusted placeholder fails closed)
# Global copy of original args (needed in update re-exec; must not be local)
ORIGINAL_ARGS=()
# Flag to signal installer re-run after checksum auto-fix
RERUN_AFTER_FIX=0
# Validate bash version (requires 4.0+)
if ((BASH_VERSINFO[0] < 4)); then
# Attempt macOS auto-remediation via Homebrew
if [[ "$(uname -s)" == "Darwin" ]] && command -v brew >/dev/null 2>&1; then
BREW_PREFIX="$(brew --prefix)"
POTENTIAL_BASH="${BREW_PREFIX}/bin/bash"
FOUND_VALID_BASH=0
if [[ -x "$POTENTIAL_BASH" ]]; then
POTENTIAL_VER="$("$POTENTIAL_BASH" -c 'echo "${BASH_VERSINFO[0]}"' 2>/dev/null)"
if [[ "$POTENTIAL_VER" =~ ^[0-9]+$ ]] && (( POTENTIAL_VER >= 4 )); then
FOUND_VALID_BASH=1
fi
fi
SHOULD_UPGRADE=0
NEEDS_INSTALL=1
if [[ "$FOUND_VALID_BASH" -eq 1 ]]; then
SHOULD_UPGRADE=1
NEEDS_INSTALL=0
else
# Check for easy mode in args (before parsing)
IS_EASY=0
for arg in "$@"; do [[ "$arg" == "--easy-mode" ]] && IS_EASY=1; done
if [[ "$IS_EASY" -eq 1 ]]; then
SHOULD_UPGRADE=1
else
# Prompt user using /dev/tty to handle piped execution
if [ -c /dev/tty ]; then
echo "Error: macOS ships with Bash 3.2, but UBS requires 4.0+."
echo -ne "Install modern Bash via Homebrew? (y/N): " > /dev/tty
read -r REPLY < /dev/tty
if [[ "$REPLY" =~ ^[Yy]$ ]]; then SHOULD_UPGRADE=1; fi
fi
fi
fi
if [[ "$SHOULD_UPGRADE" -eq 1 ]]; then
if [[ "$NEEDS_INSTALL" -eq 1 ]]; then
echo "Upgrading Bash via Homebrew..."
brew install bash
fi
NEW_BASH="$(brew --prefix)/bin/bash"
if [[ -x "$NEW_BASH" ]]; then
# Configure zsh alias if using zsh
if [[ "${SHELL:-}" == *"zsh"* ]]; then
RC_FILE="${HOME}/.zshrc"
if [ -f "$RC_FILE" ] && ! grep -q "alias bash=" "$RC_FILE"; then
echo "" >> "$RC_FILE"
echo "# Added by Ultimate Bug Scanner Installer" >> "$RC_FILE"
echo "alias bash='$NEW_BASH'" >> "$RC_FILE"
echo "Added bash alias to $RC_FILE"
fi
fi
echo "Re-launching installer with modern Bash..."
if [[ -f "$0" ]]; then
exec "$NEW_BASH" "$0" "$@"
else
# Piped execution - fetch, run, and clean up
TEMP_SCRIPT=$(mktemp "${TMPDIR:-/tmp}/ubs-install.XXXXXX")
curl -fsSL "${REPO_URL}/install.sh" -o "$TEMP_SCRIPT"
"$NEW_BASH" "$TEMP_SCRIPT" "$@"
EXIT_CODE=$?
rm -f "$TEMP_SCRIPT"
exit $EXIT_CODE
fi
else
echo "Error: Failed to locate Homebrew bash at $NEW_BASH" >&2
fi
fi
fi
echo "Error: This installer requires Bash 4.0 or later (you have $BASH_VERSION)" >&2
echo "Please upgrade bash or install manually." >&2
exit 1
fi
# TTY-aware color initialization
COLOR_ENABLED=1
init_colors() {
if [ -n "${NO_COLOR:-}" ] || [ ! -t 1 ] || [ "${TERM:-dumb}" = "dumb" ]; then COLOR_ENABLED=0; fi
if [ "$COLOR_ENABLED" -eq 1 ]; then
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; BOLD='\033[1m'; RESET='\033[0m'
else
RED=''; GREEN=''; YELLOW=''; BLUE=''; BOLD=''; RESET=''
fi
}
init_colors
# Symbols
CHECK="${GREEN}✓${RESET}"
CROSS="${RED}✗${RESET}"
ARROW="${BLUE}→${RESET}"
WARN="${YELLOW}⚠${RESET}"
# Flags
NON_INTERACTIVE=0
EASY_MODE=0
QUIET=0
SYSTEM_WIDE=0
NO_PATH_MODIFY=0
SKIP_AST_GREP=0
SKIP_RIPGREP=0
SKIP_JQ=0
SKIP_TYPOS=0
SKIP_BUN=0
SKIP_TYPE_NARROWING=0
TYPE_NARROWING_READY=0
SKIP_HOOKS=0
AUTO_UPDATE=0
INSTALL_DIR=""
FORCE_REINSTALL=0
FORCE_UNINSTALL=0
SKIP_VERSION_CHECK=0
RUN_VERIFICATION=1
DRY_RUN=0
RUN_SELF_TEST=0
RUN_DOCTOR=1
INSECURE=0
CHECKSUM_FILE=""
CHECKSUM_SIG_FILE=""
SESSION_AGENT_SUMMARY=""
SESSION_SUMMARY_FILE=""
declare -a SESSION_FACT_KEYS=()
declare -A SESSION_FACTS=()
# Temporary files tracking for cleanup
TEMP_FILES=()
# Temporary working directory for this run (isolates artifacts; pruned on EXIT)
WORKDIR_CAN_DELETE=1
# Lock file for concurrent execution prevention (MUST be fixed name, not $$)
LOCK_FILE="/tmp/ubs-install.lock"
# Track if we own the lock (only remove it if we created it)
LOCK_OWNED=0
LOCK_METHOD="dir"
LOCK_FD=""
dry_run_enabled() { [ "$DRY_RUN" -eq 1 ]; }
log_dry_run() {
local message="$1"
log "[dry-run] $message"
}
log_section() {
local title="$1"
echo ""
echo -e "${BOLD}${BLUE}╔═════════════════════════════════════════════════════╗${RESET}"
printf "${BOLD}${BLUE}║ %-51s ║${RESET}\n" "$title"
echo -e "${BOLD}${BLUE}╚═════════════════════════════════════════════════════╝${RESET}"
}
record_session_fact() {
local key="$1"
local value="$2"
[ -z "$key" ] && return 0
local exists=0
for existing in "${SESSION_FACT_KEYS[@]}"; do
if [ "$existing" = "$key" ]; then
exists=1
break
fi
done
if [ "$exists" -eq 0 ]; then
SESSION_FACT_KEYS+=("$key")
fi
SESSION_FACTS["$key"]="$value"
}
record_tool_status() {
local label="$1"
local skip_flag="$2"
local check_fn="$3"
local skip_reason="$4"
if [ "$skip_flag" -eq 1 ]; then
record_session_fact "$label" "skipped (${skip_reason})"
elif "$check_fn" >/dev/null 2>&1; then
record_session_fact "$label" "installed"
else
record_session_fact "$label" "missing"
fi
}
print_help_option() {
local flag="$1"
local description="$2"
printf " %-24s %s\n" "$flag" "$description"
}
show_help() {
cat <<'HELP'
Usage: install.sh [OPTIONS]
HELP
echo "Core workflow:"
print_help_option "--easy-mode" "Accept all prompts, install deps, and wire integrations"
print_help_option "--non-interactive" "Skip all prompts (use defaults)"
print_help_option "--update" "Force reinstall to latest version"
print_help_option "--install-dir DIR" "Custom installation directory"
print_help_option "--system" "Install to /usr/local/bin (uses sudo if needed)"
print_help_option "--no-path-modify" "Skip shell RC edits and alias creation"
echo ""
echo "Safety & diagnostics:"
print_help_option "--dry-run" "Log every action without modifying the system"
print_help_option "--self-test" "Run installer smoke tests after install"
print_help_option "--skip-version-check" "Do not check GitHub for newer releases"
print_help_option "--skip-verification" "Skip checksum/signature verification (NOT recommended)"
print_help_option "--insecure" "Bypass all integrity checks (NOT recommended)"
print_help_option "--info" "Print installer release + key metadata and exit"
print_help_option "--diagnose" "Print environment + dependency diagnostics"
print_help_option "--generate-config" "Create ~/.config/ubs/install.conf"
echo ""
echo "Dependency controls:"
print_help_option "--skip-ast-grep" "Skip ast-grep installation (JS/TS accuracy reduced)"
print_help_option "--skip-ripgrep" "Skip ripgrep installation"
print_help_option "--skip-jq" "Skip jq installation"
print_help_option "--skip-typos" "Skip typos installation"
print_help_option "--skip-bun" "Skip bun installation (used for TypeScript)"
print_help_option "--skip-type-narrowing" "Skip Node/TypeScript readiness probe"
print_help_option "--skip-doctor" "Skip running 'ubs doctor' after install"
echo ""
echo "Integrations:"
print_help_option "--skip-hooks" "Skip hook/setup prompts"
print_help_option "--setup-git-hook" "Only (re)install git hook"
print_help_option "--setup-claude-hook" "Only install Claude on-save hook"
echo ""
echo "Output & UX:"
print_help_option "--quiet" "Reduce installer output"
print_help_option "--no-color" "Disable ANSI colors"
print_help_option "--uninstall" "Remove UBS and integrations"
print_help_option "--help" "Show this help"
echo ""
}
report_type_narrowing_status() {
TYPE_NARROWING_READY=0
if [ "$SKIP_TYPE_NARROWING" -eq 1 ]; then
log "[skip] Type narrowing readiness check disabled via --skip-type-narrowing"
return 0
fi
if dry_run_enabled; then
log_dry_run "Would check Node.js + TypeScript readiness for type narrowing."
return 0
fi
if ! check_node; then
warn " Node.js not found – TypeScript-based narrowing will fall back to heuristic mode"
return 0
fi
if check_typescript_pkg; then
success " TypeScript compiler detected (type narrowing ready)"
TYPE_NARROWING_READY=1
else
warn " TypeScript package not found – run 'npm install -g typescript' or add it to your project devDependencies"
fi
return 0
}
count_swift_files() {
local dir="$1"
local count=0
if command -v rg >/dev/null 2>&1; then
count=$(rg --files "$dir" -g '*.swift' 2>/dev/null | wc -l | awk 'END{print $1+0}')
else
count=$(find "$dir" -type f -name '*.swift' 2>/dev/null | wc -l | awk 'END{print $1+0}')
fi
echo "$count"
}
report_swift_guard_readiness() {
echo -e "${BOLD}Swift guard readiness:${RESET}"
if [ "$SKIP_TYPE_NARROWING" -eq 1 ]; then
log " [skip] Swift guard helper disabled via --skip-type-narrowing"
record_session_fact "swift guard helper" "skipped (--skip-type-narrowing)"
echo ""
return 0
fi
if ! command -v python3 >/dev/null 2>&1; then
warn " python3 not found – Swift guard helper requires python3"
record_session_fact "swift guard helper" "python3 missing"
echo ""
return 0
fi
local scan_root="$PWD"
if [ -n "${PROJECT_DIR:-}" ] && [ -d "$PROJECT_DIR" ]; then
scan_root="$PROJECT_DIR"
fi
local swift_count
swift_count=$(count_swift_files "$scan_root")
if [ "$swift_count" -gt 0 ]; then
success " Swift files detected under $scan_root: $swift_count (guard helper active)"
record_session_fact "swift guard helper" "$swift_count Swift files detected (helper ready)"
else
log " No Swift files detected under $scan_root (helper idle until Swift code appears)"
record_session_fact "swift guard helper" "no Swift files detected (idle)"
fi
echo ""
return 0
}
register_temp_path() {
local path="$1"
TEMP_FILES+=("$path")
}
mktemp_in_workdir() {
local template="${1:-ubs.XXXXXX}"
local path
path="$(mktemp -p "$WORKDIR" "$template" 2>/dev/null || mktemp "${WORKDIR}/${template}")"
register_temp_path "$path"
echo "$path"
}
mktemp_dir_in_workdir() {
local template="${1:-ubs.XXXXXX}"
local path
path="$(mktemp -d -p "$WORKDIR" "$template" 2>/dev/null || mktemp -d "${WORKDIR}/${template}")"
register_temp_path "$path"
echo "$path"
}
safe_remove_temp() {
local target="$1"
[[ -z "$target" ]] && return 0
case "$target" in
"/") warn "Refusing to remove /"; return 0 ;;
".") warn "Refusing to remove current directory"; return 0 ;;
*)
# Only allow removal of files we created under WORKDIR.
if [[ "$target" != "$WORKDIR" && "$target" != "$WORKDIR"/* ]]; then
return 0
fi
;;
esac
rm -rf "$target" 2>/dev/null || true
}
cleanup_on_exit() {
# Clean up temporary files
if [ ${#TEMP_FILES[@]} -gt 0 ]; then
for temp_file in "${TEMP_FILES[@]}"; do
safe_remove_temp "$temp_file"
done
fi
if [ -n "${WORKDIR:-}" ] && [ "$WORKDIR_CAN_DELETE" -eq 1 ]; then
# Allow cleanup for installer-managed workdir
rm -rf "$WORKDIR" 2>/dev/null || true
fi
release_lock
}
release_lock() {
if [ "$LOCK_OWNED" -eq 1 ]; then
rmdir "$LOCK_FILE" 2>/dev/null || true
LOCK_OWNED=0
fi
}
acquire_lock() {
# Use a directory lock for safety. File-based locks in /tmp can follow symlinks
# and truncate arbitrary files if the installer is run with elevated privileges.
LOCK_METHOD="dir"
if mkdir "$LOCK_FILE" 2>/dev/null; then
LOCK_OWNED=1
return 0
else
error "Another installation is already in progress."
error "If this is incorrect, delete $LOCK_FILE and retry."
exit 1
fi
}
print_header() {
[ "$QUIET" -eq 1 ] && return 0
echo -e "${BOLD}${BLUE}"
cat << 'HEADER'
╔══════════════════════════════════════════════════════════════════╗
║ ║
║ ██╗ ██╗██████╗ ███████╗ ██╗███╗ ██╗███████╗████████╗ ║
║ ██║ ██║██╔══██╗██╔════╝ ██║████╗ ██║██╔════╝╚══██╔══╝ ║
║ ██║ ██║██████╔╝███████╗ ██║██╔██╗ ██║███████╗ ██║ ║
║ ██║ ██║██╔══██╗╚════██║ ██║██║╚██╗██║╚════██║ ██║ ║
║ ╚██████╔╝██████╔╝███████║ ██║██║ ╚████║███████║ ██║ ║
║ ╚═════╝ ╚═════╝ ╚══════╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ║
║ ║
HEADER
echo -e " ║ ${GREEN}🔬 ULTIMATE BUG SCANNER INSTALLER v${VERSION} 🔬${BLUE} ║"
cat << 'HEADER'
║ ║
║ Industrial-Grade Static Analysis for Polyglot AI Codebases ║
║ Catch 1000+ Bug Patterns Before Production ║
║ ║
╚══════════════════════════════════════════════════════════════════╝
HEADER
echo -e "${RESET}"
}
print_with_icon() {
local icon="$1"
shift || true
local message="$*"
if [ -z "$message" ]; then
printf "%b\n" "$icon"
return 0
fi
local prefix="$icon"
local indent=" "
while IFS= read -r line || [ -n "$line" ]; do
printf "%b %s%s\n" "$prefix" "$indent" "$line"
prefix=" "
done <<<"$message"
}
log() { print_with_icon "${ARROW}" "$*"; }
success() { print_with_icon "${CHECK}" "$*"; }
error() { print_with_icon "${CROSS}" "$*" >&2; }
warn() { print_with_icon "${WARN}" "$*"; }
# Secure download helpers
secure_fetch() {
local url="$1" out="$2" err_file="$3"
if command -v curl >/dev/null 2>&1; then
curl --fail --location --proto '=https' --tlsv1.2 --retry 3 --retry-delay 1 --compressed -o "$out" "$url" 2>"$err_file"
else
wget --https-only --secure-protocol=TLSv1_2 --tries=3 --waitretry=1 --timeout=20 -O "$out" "$url" 2>"$err_file"
fi
}
# Compute SHA256 digest in a portable way (Linux + macOS).
compute_sha256() {
local file="$1"
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$file" | awk '{print $1}'
elif command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$file" | awk '{print $1}'
elif command -v openssl >/dev/null 2>&1; then
openssl dgst -sha256 "$file" | awk '{print $NF}'
else
return 1
fi
}
fetch_checksum_bundle() {
if [ "$RUN_VERIFICATION" -eq 0 ] || [ "$INSECURE" -eq 1 ]; then
return 0
fi
local sums="$WORKDIR/SHA256SUMS"
local sig="$WORKDIR/SHA256SUMS.minisig"
local err
err=$(mktemp_in_workdir "checksums.err.XXXXXX")
log "Fetching signed checksums from release artifacts..."
if ! secure_fetch "${ARTIFACT_BASE}/SHA256SUMS" "$sums" "$err"; then
log_network_failure "Failed to download SHA256SUMS from ${ARTIFACT_BASE}" "$err"
error "Checksum download failed. Use --insecure to bypass (not recommended)."
exit 1
fi
if ! secure_fetch "${ARTIFACT_BASE}/SHA256SUMS.minisig" "$sig" "$err"; then
log_network_failure "Failed to download SHA256SUMS.minisig from ${ARTIFACT_BASE}" "$err"
error "Checksum signature download failed. Use --insecure to bypass (not recommended)."
exit 1
fi
if [ -z "$MINISIGN_PUBKEY" ]; then
error "MINISIGN public key not configured. Set UBS_MINISIGN_PUBKEY or rerun with --insecure."
exit 1
fi
if ! command -v minisign >/dev/null 2>&1; then
error "minisign is required for signature verification (install via your package manager)."
exit 1
fi
if ! command -v sha256sum >/dev/null 2>&1 && ! command -v shasum >/dev/null 2>&1 && ! command -v openssl >/dev/null 2>&1; then
error "No SHA256 tool found (need sha256sum, shasum, or openssl)."
exit 1
fi
if minisign -Vm "$sums" -P "$MINISIGN_PUBKEY" -x "$sig" >/dev/null 2>&1; then
CHECKSUM_FILE="$sums"
CHECKSUM_SIG_FILE="$sig"
success "Checksum signature verified"
else
error "Signature verification failed for SHA256SUMS"
exit 1
fi
}
verify_download_checksum() {
local file_path="$1" expected_name="$2"
if [ "$RUN_VERIFICATION" -eq 0 ] || [ "$INSECURE" -eq 1 ]; then
return 0
fi
if [ -z "$CHECKSUM_FILE" ] || [ ! -f "$CHECKSUM_FILE" ]; then
error "Checksum file not available; cannot verify ${expected_name}."
exit 1
fi
local tmp_sum
tmp_sum=$(mktemp_in_workdir "${expected_name}.sha.XXXXXX")
if ! grep " ${expected_name}$" "$CHECKSUM_FILE" > "$tmp_sum"; then
error "Checksum entry for ${expected_name} missing in SHA256SUMS"
exit 1
fi
local expected_sum actual_sum
expected_sum="$(awk '{print $1}' "$tmp_sum" | head -n 1)"
if ! actual_sum="$(compute_sha256 "$file_path")"; then
error "No SHA256 tool found (need sha256sum, shasum, or openssl) to verify ${expected_name}."
exit 1
fi
if [[ "$expected_sum" != "$actual_sum" ]]; then
error "Checksum verification failed for ${expected_name}"
error "Expected: ${expected_sum}"
error "Got: ${actual_sum}"
exit 1
fi
success "Checksum verified for ${expected_name}"
}
# Set up cleanup traps
trap 'cleanup_on_exit; exit 130' INT # 130 = 128 + SIGINT (2)
trap 'cleanup_on_exit; exit 143' TERM # 143 = 128 + SIGTERM (15)
trap cleanup_on_exit EXIT
if [ -n "${UBS_INSTALLER_WORKDIR:-}" ]; then
if [[ "${UBS_INSTALLER_WORKDIR}" = /* ]]; then
WORKDIR="${UBS_INSTALLER_WORKDIR}"
else
WORKDIR="$PWD/${UBS_INSTALLER_WORKDIR}"
fi
if [ -e "$WORKDIR" ]; then
error "UBS_INSTALLER_WORKDIR path already exists: $WORKDIR"
error "Provide a non-existent directory so the installer can manage its lifecycle safely."
exit 1
fi
if ! mkdir -p "$WORKDIR" 2>/dev/null; then
error "Unable to create installer work directory: $WORKDIR"
exit 1
fi
else
# GNU mktemp requires X placeholders when using -t; macOS adds them automatically.
# Provide explicit template so both implementations succeed.
WORKDIR="$(mktemp -d 2>/dev/null || mktemp -d -t ubs-install.XXXXXX)"
fi
TEMP_FILES+=("$WORKDIR")
log_network_failure() {
local context="$1"
local err_file="$2"
warn "$context"
if [ -n "$err_file" ] && [ -s "$err_file" ]; then
warn " Last error: $(tail -n 1 "$err_file")"
fi
}
warn_path_shadow() {
local expected="$1"
local actual="$2"
warn "PATH resolves 'ubs' to $actual, but installer just wrote $expected."
warn "Update PATH or remove old binaries so the new version is used."
}
ask() {
local prompt="$1"
if [ "$EASY_MODE" -eq 1 ]; then
log "Easy mode: auto-accepting prompt -> ${prompt}"
return 0
fi
if [ "$NON_INTERACTIVE" -eq 1 ]; then
return 1 # Default to "no" in non-interactive mode
fi
local response
# Method 1: Try /dev/tty if available (best for curl | bash)
if [ -c /dev/tty ]; then
# Explicitly write to tty. If this fails (e.g. no write perms), we fall through.
if echo -ne "${YELLOW}?${RESET} ${prompt} (y/N): " > /dev/tty 2>/dev/null; then
if read -r response < /dev/tty; then
[[ "$response" =~ ^[Yy]$ ]]
return $?
fi
fi
fi
# Method 2: Try stdin if it's a TTY
if [ -t 0 ]; then
# Stdin is a terminal, so we can prompt and read normally
if read -r -p "$(echo -e "${YELLOW}?${RESET} ${prompt} (y/N): ")" response; then
[[ "$response" =~ ^[Yy]$ ]]
return $?
fi
fi
# Method 3: No interactive channel available
# This happens if running non-interactively (e.g. cron, non-tty pipe)
# and we failed to access /dev/tty.
warn "Cannot prompt for input (stdin is not a TTY and /dev/tty unavailable)."
warn "Run with --non-interactive to accept defaults, or --easy-mode."
return 1
}
with_backoff() {
# with_backoff <max_attempts> <cmd...>
local max="${1:-3}"; shift || true
local n=1 delay=1
while true; do
if "$@"; then return 0; fi
if (( n >= max )); then return 1; fi
sleep "$delay"
n=$((n+1)); delay=$((delay*2))
done
}
maybe_sudo() { local path="$1"; if [ -w "$path" ]; then echo ""; elif can_use_sudo; then echo "sudo"; else echo ""; fi }
can_use_sudo() {
# Check if sudo is available and can be used without password prompt
if ! command -v sudo >/dev/null 2>&1; then
return 1
fi
# Check if we can run sudo -n (non-interactive)
if sudo -n true 2>/dev/null; then
return 0
fi
# If interactive mode, we can potentially use sudo with password
if [ "$NON_INTERACTIVE" -eq 0 ]; then
return 0
fi
return 1
}
is_windows_admin() {
# Best-effort check: net session succeeds only when elevated
if command -v net.exe >/dev/null 2>&1; then
if net.exe session >/dev/null 2>&1; then
return 0
fi
fi
return 1
}
safe_timeout() {
# Cross-platform timeout wrapper
# Usage: safe_timeout <seconds> <command> [args...]
# Returns: command exit code, or 124 if timeout occurred
local timeout_duration="$1"
shift
# Try GNU timeout first (Linux, some BSD with coreutils)
if command -v timeout >/dev/null 2>&1; then
timeout "$timeout_duration" "$@"
return $?
fi
# Try gtimeout (macOS with coreutils via brew)
if command -v gtimeout >/dev/null 2>&1; then
gtimeout "$timeout_duration" "$@"
return $?
fi
# Fallback: bash-based timeout implementation for macOS/BSD
"$@" &
local pid=$!
# Wait for process with timeout
local count=0
while kill -0 $pid 2>/dev/null; do
if [ $count -ge "$timeout_duration" ]; then
# Kill the process group in case the tool spawned children
kill -TERM -$pid 2>/dev/null || kill -TERM $pid 2>/dev/null
sleep 1
kill -KILL -$pid 2>/dev/null || kill -KILL $pid 2>/dev/null
wait $pid 2>/dev/null
return 124 # Standard timeout exit code
fi
sleep 1
((count++))
done
# Get actual exit status
wait $pid
return $?
}
detect_platform() {
local os
os="$(uname -s)"
# WSL detection (uname shows Linux, but /proc/version mentions Microsoft)
if [[ "$os" == "Linux" ]] && grep -qi microsoft /proc/version 2>/dev/null; then
echo "wsl"
return 0
fi
case "$os" in
Linux*) echo "linux" ;;
Darwin*) echo "macos" ;;
FreeBSD*) echo "freebsd" ;;
OpenBSD*) echo "openbsd" ;;
NetBSD*) echo "netbsd" ;;
CYGWIN*|MINGW*|MSYS*) echo "windows" ;;
*) echo "unknown" ;;
esac
}
detect_shell() {
if [ -n "${BASH_VERSION:-}" ]; then
echo "bash"
elif [ -n "${ZSH_VERSION:-}" ]; then
echo "zsh"
elif [[ "${SHELL:-}" == *"fish"* ]]; then
echo "fish"
else
# Check default shell
basename "$SHELL"
fi
}
get_rc_file() {
local shell_type
shell_type="$(detect_shell)"
case "$shell_type" in
bash)
if [ -f "$HOME/.bashrc" ]; then
echo "$HOME/.bashrc"
else
echo "$HOME/.bash_profile"
fi
;;
fish)
echo "$HOME/.config/fish/config.fish"
;;
zsh)
echo "$HOME/.zshrc"
;;
*)
echo "$HOME/.profile"
;;
esac
}
check_ast_grep() {
if command -v ast-grep >/dev/null 2>&1; then
return 0
fi
# Verify 'sg' is actually ast-grep, not the Unix newgrp command
if command -v sg >/dev/null 2>&1 && sg --version 2>&1 | grep -qi "ast-grep"; then
return 0
fi
return 1
}
install_ast_grep() {
local platform
platform="$(detect_platform)"
log "Installing ast-grep..."
if dry_run_enabled; then
log_dry_run "Would install ast-grep (platform $platform)."
return 0
fi
local log_file
log_file="$(mktemp_in_workdir "ast-grep-install.log.XXXXXX")"
case "$platform" in
macos)
if command -v brew >/dev/null 2>&1; then
log "Attempting installation via Homebrew..."
if brew install ast-grep 2>&1 | tee "$log_file"; then
success "ast-grep installed via Homebrew"
return 0
fi
warn "Homebrew installation failed (see $log_file). Trying binary download..."
else
warn "Homebrew not found. Trying binary download..."
fi
if download_binary_release "ast-grep" "$platform"; then
return 0
fi
error "All installation methods failed on macOS"
log "Install manually from: https://ast-grep.github.io/guide/quick-start.html"
return 1
;;
wsl|linux)
if [ "$platform" = "wsl" ]; then
log "Detected WSL environment - using Linux package managers"
fi
if command -v cargo >/dev/null 2>&1; then
log "Attempting installation via cargo..."
if cargo install ast-grep 2>&1 | tee "$log_file"; then
success "ast-grep installed via cargo"
return 0
else
warn "Cargo installation failed, trying npm..."
fi
fi
if command -v npm >/dev/null 2>&1; then
log "Attempting installation via npm..."
if npm install -g @ast-grep/cli 2>&1 | tee "$log_file"; then
success "ast-grep installed via npm"
return 0
else
warn "npm installation failed"
fi
fi
warn "Package managers failed. Trying binary download..."
if download_binary_release "ast-grep" "$platform"; then
return 0
fi
error "All installation methods failed"
log "Download manually from: https://github.com/ast-grep/ast-grep/releases"
return 1
;;
freebsd|openbsd|netbsd)
log "BSD platform detected: $platform"
if command -v cargo >/dev/null 2>&1; then
log "Attempting installation via cargo..."
if cargo install ast-grep 2>&1 | tee "$log_file"; then
success "ast-grep installed via cargo"
return 0
fi
fi
if command -v npm >/dev/null 2>&1; then
log "Attempting installation via npm..."
if npm install -g @ast-grep/cli 2>&1 | tee "$log_file"; then
success "ast-grep installed via npm"
return 0
fi
fi
warn "Package managers failed. Trying binary download..."
if download_binary_release "ast-grep" "$platform"; then
return 0
fi
error "All installation methods failed for BSD"
log "Download manually from: https://github.com/ast-grep/ast-grep/releases"
return 1
;;
windows)
if command -v cargo >/dev/null 2>&1; then
if cargo install ast-grep 2>&1 | tee "$log_file"; then
success "ast-grep installed via cargo"
return 0
else
warn "Cargo installation failed, trying binary download..."
fi
fi
if download_binary_release "ast-grep" "$platform"; then
return 0
fi
warn "Install Rust/Cargo or download from: https://ast-grep.github.io/"
return 1
;;
*)
error "Unknown platform. Install manually from: https://ast-grep.github.io/"
return 1
;;
esac
}
check_ripgrep() { command -v rg >/dev/null 2>&1; }
check_jq() { command -v jq >/dev/null 2>&1; }
check_typos() { command -v typos >/dev/null 2>&1; }
# ==============================================================================
# TIER 1 ENHANCEMENTS: Version Checking, Binary Fallbacks, Verification
# ==============================================================================
version_compare() {
# Compare two version strings using semantic versioning
# Returns: 0 if $1 > $2, 1 if $1 <= $2
local ver1="${1#v}"
local ver2="${2#v}"
if [ "$ver1" = "$ver2" ]; then return 1; fi
if echo -e "2.0\n1.0" | sort -V >/dev/null 2>&1; then
local first
first=$(printf '%s\n' "$ver1" "$ver2" | sort -V | head -n1)
if [ "$first" = "$ver2" ] && [ "$ver1" != "$ver2" ]; then return 0; else return 1; fi
fi
# Fallback numeric-only compare: strip non-digits from components
local clean1="${ver1//[^0-9.]/.}"
local clean2="${ver2//[^0-9.]/.}"
IFS='.' read -r -a v1 <<< "$clean1"
IFS='.' read -r -a v2 <<< "$clean2"
local n=${#v1[@]}
local len2=${#v2[@]}
if [ "$len2" -gt "$n" ]; then
n="$len2"
fi
for ((i=0;i<n;i++)); do
local a="${v1[i]:-0}" b="${v2[i]:-0}"
a=$((10#$a)); b=$((10#$b))
if ((a>b)); then return 0; elif ((a<b)); then return 1; fi
done
return 1
}
check_for_updates() {
[ "$SKIP_VERSION_CHECK" -eq 1 ] && return 0
local current_version="$VERSION"
local latest_url="$REPO_URL/VERSION"
local err_log latest_file
err_log="$(mktemp_in_workdir "update.err.XXXXXX")"
latest_file="$(mktemp_in_workdir "version.latest.XXXXXX")"
log "Checking for updates..."
local latest_version
if with_backoff 3 curl -fsSL --max-time 5 "$latest_url" -o "$latest_file" 2>"$err_log"; then
latest_version=$(tr -d '[:space:]' < "$latest_file")
if version_compare "$latest_version" "$current_version"; then
warn "New version available: $latest_version (you have $current_version)"
if ask "Update to latest version now?"; then
log "Re-running installer with latest version..."
release_lock
if [ "${#ORIGINAL_ARGS[@]}" -gt 0 ]; then
exec bash <(curl -fsSL "$REPO_URL/install.sh") "${ORIGINAL_ARGS[@]}"
else
exec bash <(curl -fsSL "$REPO_URL/install.sh")
fi
error "Failed to download or execute updated installer"
exit 1
fi
else
success "You have the latest version ($current_version)"
fi
else
log_network_failure "Could not check for updates (network issue or rate limit)" "$err_log"
fi
}
download_binary_release() {
local tool="$1" # ast-grep, ripgrep, or jq
local platform="$2"
local arch
arch="$(uname -m)"
case "$arch" in
x86_64|amd64) arch="x86_64" ;;
aarch64|arm64) arch="aarch64" ;;
armv7*) arch="armv7" ;;
*) error "Unsupported architecture: $arch"; return 1 ;;
esac
local install_dir="$HOME/.local/bin"
mkdir -p "$install_dir" 2>/dev/null || { error "Cannot create $install_dir"; return 1; }
if dry_run_enabled; then
log_dry_run "Would download binary for $tool ($platform-$arch)."
return 0