-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathiiab-termux
More file actions
executable file
·4044 lines (3459 loc) · 132 KB
/
Copy pathiiab-termux
File metadata and controls
executable file
·4044 lines (3459 loc) · 132 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
#!/data/data/com.termux/files/usr/bin/bash
set -euo pipefail
# -----------------------------------------------------------------------------
# GENERATED FILE: 2026-05-06T08:30:49-06:00 - do not edit directly.
# Source modules: termux-setup/*.sh + manifest.sh
# Rebuild: (cd termux-setup && bash build_bundle.sh)
# -----------------------------------------------------------------------------
# ---- BEGIN 00_lib_common.sh ----
# shellcheck shell=bash
# Module file (no shebang). Bundled by build_bundle.sh
RED="\033[31m"; YEL="\033[33m"; GRN="\033[32m"; BLU="\033[34m"; RST="\033[0m"; BOLD="\033[1m"
log() { printf "${BLU}[iiab]${RST} %s\n" "$*"; }
log_red() { printf "${RED}[iiab]${RST} %s\n" "$*"; }
log_yel() { printf "${YEL}[iiab]${RST} %s\n" "$*"; }
ok() { printf "${GRN}[iiab]${RST} %s\n" "$*"; }
warn() { printf "${YEL}[iiab] WARNING:${RST} %s\n" "$*" >&2; }
warn_red() { printf "${RED}${BOLD}[iiab] WARNING:${RST} %s\n" "$*" >&2; }
boxyp_log() { printf "${BLU}[boxyproxy]${RST} %s\n" "$*"; }
indent() { sed 's/^/ /'; }
have() { command -v "$1" >/dev/null 2>&1; }
need() { have "$1" || return 1; }
die() { printf "${RED}[!] ERROR${RST}: %s\n" "$*" >&2; exit 1; }
blank() {
local n="${1:-1}" fd=1
[[ "$n" =~ ^[0-9]+$ ]] || n=1
if { : >&3; } 2>/dev/null; then fd=3; fi
while (( n-- > 0 )); do printf '\n' >&"$fd"; done
}
clear_line() {
local outfd; outfd="$(console_outfd)"
printf "\r%-80s\r" " " >&"$outfd"
}
# Choose warning level depending on context.
# - In explicit readiness checks (--check/--all), use red for "will likely fail".
# - In passive/self-check (baseline runs), keep it yellow to avoid over-alarming.
warn_red_context() {
# args: long message
if [[ "${MODE:-}" == "check" || "${MODE:-}" == "all" || "${MODE:-}" == "ppk-only" ]]; then
warn_red "$*"
else
warn "$*"
fi
}
# -------------------------
# Global defaults (may be overridden via environment)
# -------------------------
STATE_DIR="${STATE_DIR:-${HOME}/.iiab-android}"
ADB_STATE_DIR="${ADB_STATE_DIR:-${STATE_DIR}/adbw_pair}"
LOG_DIR="${LOG_DIR:-${STATE_DIR}/logs}"
HOST="${HOST:-127.0.0.1}"
CONNECT_PORT="${CONNECT_PORT:-}"
TIMEOUT_SECS="${TIMEOUT_SECS:-180}"
# -------------------------
# Android App State Sync (Controller Communication)
# -------------------------
ANDROID_SHARED_STATE_DIR="/sdcard/.iiab_state"
set_android_state_flag() {
local flag_name="$1"
# Only attempt if /sdcard is accessible
if [[ -d "/sdcard" ]]; then
mkdir -p "$ANDROID_SHARED_STATE_DIR" 2>/dev/null || true
touch "${ANDROID_SHARED_STATE_DIR}/${flag_name}" 2>/dev/null || true
fi
}
clear_android_state_flag() {
local flag_name="$1"
if [[ -d "/sdcard" ]]; then
rm -f "${ANDROID_SHARED_STATE_DIR}/${flag_name}" 2>/dev/null || true
fi
}
# Defaults used by ADB flows / logging / misc
CLEANUP_OFFLINE="${CLEANUP_OFFLINE:-1}"
DEBUG="${DEBUG:-0}"
BOXYPROXY_NO_EXTERNAL="${BOXYPROXY_NO_EXTERNAL:-0}"
# Package name for the Termux app.
TERMUX_PACKAGE="${TERMUX_PACKAGE:-com.termux}"
# Version and Update logic
IIAB_TERMUX_RAW_URL="${IIAB_TERMUX_RAW_URL:-https://raw.githubusercontent.com/iiab/iiab-android/main/iiab-termux}"
# Android info
get_android_sdk() { getprop ro.build.version.sdk 2>/dev/null || true; }
get_android_release() { getprop ro.build.version.release 2>/dev/null || true; }
ANDROID_SDK="$(get_android_sdk)"
ANDROID_REL="$(get_android_release)"
# Default URLs for auto-pulling rootfs
IIAB_ROOTFS_URL_ARM64="${IIAB_ROOTFS_URL_ARM64:-https://iiab.switnet.org/android/rootfs/latest_arm64-v8a.meta4}"
IIAB_ROOTFS_URL_ARM32="${IIAB_ROOTFS_URL_ARM32:-https://iiab.switnet.org/android/rootfs/latest_armeabi-v7a.meta4}"
get_iiab_termux_version() {
local file="${1:-$0}"
local raw_ts=""
if [[ -f "$file" ]]; then
raw_ts="$(grep '^# GENERATED FILE:' "$file" 2>/dev/null | sed -E 's/.*GENERATED FILE: ([^ ]+).*/\1/' | head -n1)"
if [[ -n "$raw_ts" ]]; then
# Convert ISO 8601 to YYYY.DDD.HHMM in UTC
# %Y = Year, %j = Day of year (001-366), %H%M = Hours/Minutes
date -u -d "$raw_ts" +"%Y.%j.%H%M" 2>/dev/null && return 0
fi
fi
echo "unknown"
}
update_iiab_termux() {
local current_file="${1:-$0}"
log "downloading latest version..."
have curl || { warn_red "curl is required to update. Run: pkg install curl"; return 1; }
# Use the state directory since Termux lacks a standard /tmp
local tmp_file="${STATE_DIR}/iiab-termux-update.tmp.$$"
if ! curl -fsSL --retry 5 --retry-connrefused --retry-delay 2 "$IIAB_TERMUX_RAW_URL" -o "$tmp_file"; then
warn_red "Failed to download update from $IIAB_TERMUX_RAW_URL"
rm -f "$tmp_file" >/dev/null 2>&1 || true
return 1
fi
local first_line=""
IFS= read -r first_line < "$tmp_file" || true
if [[ "$first_line" != \#!*bash* ]]; then
warn_red "Downloaded file doesn't look like a valid bash script (bad shebang)."
rm -f "$tmp_file" >/dev/null 2>&1 || true
return 1
fi
local old_v new_v backup_dir ts
old_v="$(get_iiab_termux_version "$current_file")"
new_v="$(get_iiab_termux_version "$tmp_file")"
# Compare versions if both are successfully parsed
if [[ "$old_v" != "unknown" && "$new_v" != "unknown" ]]; then
if [[ "$old_v" == "$new_v" ]]; then
ok "You already have the latest version ($old_v)."
rm -f "$tmp_file" >/dev/null 2>&1 || true
return 0
elif [[ "$old_v" > "$new_v" ]]; then
log_yel "Your local version ($old_v) appears to be newer than the repository version ($new_v)."
log_yel "You might be running local uncommitted changes."
if ! tty_yesno_default_n "[iiab] Do you want to overwrite your local version with the repository version? [y/N]: "; then
log "Update aborted by user. Keeping local version."
rm -f "$tmp_file" >/dev/null 2>&1 || true
return 0
fi
fi
fi
log "updating $new_v over $old_v"
backup_dir="${STATE_DIR}/termux"
mkdir -p "$backup_dir"
ts="$(date +%Y%m%d-%H%M%S)"
cp -f "$current_file" "${backup_dir}/iiab-termux.old.${ts}" 2>/dev/null || true
mv -f "$tmp_file" "$current_file" && chmod 700 "$current_file"
log "installed version: $new_v"
return 0
}
# One-time helper: guide user to set Termux battery policy to keep sessions alive.
POWER_MODE_BATTERY_PROMPT="${POWER_MODE_BATTERY_PROMPT:-1}" # 1=ask, 0=never ask
POWER_MODE_BATTERY_STAMP="${POWER_MODE_BATTERY_STAMP:-$STATE_DIR/stamp.termux_battery_settings}"
export PIP_EXTRA_INDEX_URL="https://iiab.switnet.org/simple"
tty_prompt_print() {
local prompt="$1" outfd=1
# Prefer original console FD3 if available (set by setup_logging)
if [[ -t 3 ]]; then
outfd=3
fi
printf '%b' "$prompt" >&"$outfd"
}
fd3_available() { : >&3 2>/dev/null; }
fd4_available() { : >&4 2>/dev/null; }
console_outfd() { fd3_available && echo 3 || echo 1; }
console_errfd() { fd4_available && echo 4 || echo 2; }
tty_yesno_default_y() {
# args: prompt
# Returns 0 for Yes, 1 for No. Default is Yes.
local prompt="$1" ans="Y" outfd
outfd="$(console_outfd)"
if [[ -r /dev/tty ]]; then
tty_prompt_print "$prompt"
if ! read -r ans < /dev/tty; then
ans="Y"
fi
else
warn "No /dev/tty available; defaulting to YES."
ans="Y"
fi
ans="${ans:-Y}"
[[ "$ans" =~ ^[Nn]$ ]] && return 1
return 0
}
tty_yesno_default_n() {
# args: prompt
# Returns 0 for Yes, 1 for No. Default is No.
local prompt="$1" ans="N" outfd
outfd="$(console_outfd)"
if [[ -r /dev/tty ]]; then
tty_prompt_print "$prompt"
read -r ans < /dev/tty || ans="N"
else
warn "No /dev/tty available; defaulting to NO."
ans="N"
fi
ans="${ans:-N}"
[[ "$ans" =~ ^[Yy]$ ]] && return 0
return 1
}
countdown_timer() {
# $1 = Seconds (e.g., 5)
# $2 = Format string with %d (e.g., "\r${YEL}Waiting %d secs...${RST}")
local secs="${1:-5}"
local msg="$2"
local outfd; outfd="$(console_outfd)"
if [[ -r /dev/tty ]]; then
for (( i=secs; i>=1; i-- )); do
printf "$msg" "$i" >&"$outfd"
sleep 1
done
clear_line
else
sleep "$secs"
fi
}
iiab_login() {
local stamp="$STATE_DIR/stamp.termux_base"
# Baseline stamp is advisory only for login (do not block).
if [[ -f "$stamp" ]]; then
ok "Baseline stamp found: $stamp"
else
warn_red "Baseline stamp not found ($stamp)."
warn "Tip: run the baseline once: iiab-termux"
fi
have proot-distro || die "proot-distro not found. Install baseline first (pkg install proot-distro or run iiab-termux)."
if ! iiab_exists; then
warn_red "IIAB Debian is not installed in proot-distro (alias 'iiab' missing)."
warn "Recommended: iiab-termux --all"
warn "Or: proot-distro install --override-alias iiab debian"
return 1
fi
# Reminder: Android battery policy must be configured before long installs.
if [[ "${POWER_MODE_BATTERY_PROMPT:-1}" -eq 1 ]]; then
local bst="$POWER_MODE_BATTERY_STAMP"
if [[ ! -f "$bst" && ! -f "${ANDROID_SHARED_STATE_DIR}/flag_perm_battery" ]]; then
warn "Reminder: for reliable long installs, set Termux -> Battery to 'Unrestricted'."
power_mode_battery_instructions
if tty_yesno_default_n "[iiab] Open Termux App info now to adjust Battery policy? [y/N]: "; then
if android_open_termux_app_info; then
tty_prompt_print "[iiab] When done, return to Termux and press Enter to continue... "
if [[ -r /dev/tty ]]; then
read -r _ </dev/tty || true
else
local outfd
outfd="$(console_outfd)"
printf "\n" >&"$outfd"
fi
date > "$bst" 2>/dev/null || true
else
warn "Unable to open Settings automatically. Open manually: Settings -> Apps -> Termux."
fi
fi
fi
fi
# Best-effort Android advice before user starts doing heavy installs inside proot.
local sdk="${ANDROID_SDK:-}"
if [[ "$sdk" =~ ^[0-9]+$ ]] && (( sdk >= 31 && sdk <= 33 )); then
# Android 12-13: PPK is a common hard failure point.
if have adb; then
adb start-server >/dev/null 2>&1 || true
if adb_pick_loopback_serial >/dev/null 2>&1; then
check_readiness || true
else
warn_red "Android 12-13: ADB is not connected, so PPK fix cannot be verified/applied."
warn "Before running the IIAB installer inside proot, run:"
ok " iiab-termux --all"
fi
else
warn_red "Android 12-13: adb is missing, so PPK fix cannot be verified/applied."
warn "Install adb (android-tools) and run:"
ok " iiab-termux --all"
fi
fi
ok "Starting IIAB Debian (via: iiab-termux --start)"
local wlan_ip; wlan_ip="$(adb_local_ipv4s_csv 2>/dev/null | cut -d, -f1)"
if [[ -n "$wlan_ip" && "$wlan_ip" != "Disconnected" && "$wlan_ip" != "0.0.0.0" ]]; then
if ! have qrencode; then
log "Installing missing dependency: libqrencode..."
termux_apt install libqrencode >/dev/null 2>&1 || true
fi
blank
log "To use your IIAB on Android over the network, please scan the following QR Code:"
qrencode -t UTF8 "http://${wlan_ip}:8085/"
blank
else
blank
warn "It seems there is no network available to share IIAB on Android over the network."
blank
fi
power_mode_login_enter || true
# Auto-start boxyproxy for the duration of this proot session.
BOXYPROXY_MANAGED=1
if boxyproxy_is_running; then
if [[ "${BOXYPROXY_NO_EXTERNAL:-0}" -eq 1 ]]; then
boxyp_log "Auto-start: restarting proxy to apply --no-external..."
boxyproxy_stop >/dev/null 2>&1 || true
boxyproxy_start >/dev/null 2>&1 || true
else
boxyp_log "Auto-start: already running (will stop on exit)."
fi
else
# Best-effort: install once if missing (avoid forcing updates every login).
if ! boxyproxy_is_installed; then
boxyp_log "Auto-start: installing boxyproxy.py (best-effort)..."
boxyproxy_install_or_update >/dev/null 2>&1 || true
fi
boxyproxy_start >/dev/null 2>&1 || true
fi
# Preserve interactivity even if logging is enabled (avoid pipes/tee issues).
local rc=0
local outfd errfd
outfd="$(console_outfd)"
errfd="$(console_errfd)"
# Don't let a non-zero exit from proot skip cleanup (set -e).
set +e
if [[ "${INTENT_MODE:-}" == "headless" ]]; then
boxyp_log "Running in APK Headless mode (no TTY, sleep infinity)"
if command -v am >/dev/null 2>&1; then
am start -n org.iiab.controller/org.iiab.controller.MainActivity >/dev/null 2>&1 || true
fi
proot-distro login iiab -- bash -lc "/usr/local/bin/pdsm start && sleep infinity"
rc=$?
elif [[ -r /dev/tty ]]; then
proot-distro login iiab </dev/tty >&"$outfd" 2>&"$errfd"
rc=$?
else
proot-distro login iiab
rc=$?
fi
set -e
# Stop proxy after leaving proot session (also covered by trap for signals).
boxyproxy_stop >/dev/null 2>&1 || true
BOXYPROXY_MANAGED=0
power_mode_login_exit || true
return $rc
}
iiab_stop() {
log "Stopping IIAB environment..."
# Stop the 'boxyproxy' proxy
boxyproxy_stop >/dev/null 2>&1 || true
# Graceful shutdown of internal services using 'pdsm'
if iiab_exists; then
log "Executing 'pdsm stop' for internal services..."
if command -v am >/dev/null 2>&1; then
am start -n org.iiab.controller/org.iiab.controller.MainActivity >/dev/null 2>&1 || true
fi
# Send the command into proot. The script won't fail if a service fails.
proot-distro login iiab -- /usr/local/bin/pdsm stop || warn "Partial failure while stopping services via pdsm."
fi
# Allow a few seconds for processes to save data and exit
sleep 3
# Final zombie cleanup
# We kill any orphaned processes pdsm might left hanging after 3 seconds
if pkill -0 -f "proot.*iiab" 2>/dev/null; then
log "Cleaning up remaining processes..."
pkill -TERM -f "proot.*iiab" || true
sleep 1
pkill -KILL -f "proot.*iiab" 2>/dev/null || true
fi
ok "All IIAB services have been successfully stopped."
}
cmd_json_vars() {
local yaml_content=""
# Extract content directly from inside PRoot
if iiab_exists; then
yaml_content="$(proot-distro login iiab -- cat /etc/iiab/local_vars.yml 2>/dev/null || true)"
fi
# If it fails or is empty, return an empty JSON
if [[ -z "$yaml_content" ]]; then
if [[ "${INTENT_MODE:-}" == "headless" ]]; then
mkdir -p "$ANDROID_SHARED_STATE_DIR" 2>/dev/null || true
echo "{}" > "${ANDROID_SHARED_STATE_DIR}/local_vars.json"
else
echo "{}"
fi
return 1
fi
# Ultra-fast parsing with awk: Looks for lines ending in _install: or _enabled: with True/False
local json_data
json_data=$(echo "$yaml_content" | awk -F':' '/^[a-zA-Z0-9_]+_(install|enabled):[ \t]+(True|False|true|false)/ {
key=$1;
val=$2;
gsub(/^[ \t]+|[ \t]+$/, "", val); # Remove leading/trailing spaces
if (tolower(val) == "true") val="true"; else val="false";
printf " \"%s\": %s,\n", key, val;
}' | sed '$ s/,$//') # Remove the trailing comma to make it valid JSON
local final_json="{\n${json_data}\n}"
# If called from the app (headless), write to the shared file. Otherwise, print to terminal.
if [[ "${INTENT_MODE:-}" == "headless" ]]; then
mkdir -p "$ANDROID_SHARED_STATE_DIR" 2>/dev/null || true
echo -e "$final_json" > "${ANDROID_SHARED_STATE_DIR}/local_vars.json"
if command -v am >/dev/null 2>&1; then
am start -n org.iiab.controller/org.iiab.controller.MainActivity >/dev/null 2>&1 || true
fi
else
echo -e "$final_json"
fi
}
cmd_install_module() {
local role="$1"
[[ -z "$role" ]] && die "You must specify a module/role to install."
log "Preparing to install module: $role"
if ! iiab_exists; then
die "IIAB Debian (alias 'iiab') is not installed."
fi
# Safety guard: Dashboard is auto-installed, it shouldn't be executed via runrole
if [[ "$role" == "dashboard" ]]; then
warn "Role '$role' is managed automatically. Skipping runrole execution."
return 0
fi
# Update local_vars.yml inside PRoot
log "Updating local_vars.yml for $role..."
proot-distro login iiab -- bash -c "
sed -i -E '/^[[:space:]]*${role}_(install|enabled)[[:space:]]*:/d' /etc/iiab/local_vars.yml
echo '${role}_install: True' >> /etc/iiab/local_vars.yml
echo '${role}_enabled: True' >> /etc/iiab/local_vars.yml
"
# Execute Ansible runrole
log "Executing Ansible runrole for $role..."
local rc=0
set +e
# Execute runrole preserving interactivity (TTY) if available
if [[ -r /dev/tty ]]; then
proot-distro login iiab < /dev/tty -- bash -lc "cd /opt/iiab/iiab && ./runrole $role"
rc=$?
else
proot-distro login iiab -- bash -lc "cd /opt/iiab/iiab && ./runrole $role"
rc=$?
fi
set -e
if (( rc == 0 )); then
ok "Module $role installed successfully!"
else
warn_red "Module $role installation failed or completed with errors (rc=$rc)."
fi
# Bounce back to Controller App if called via Android Intent
if [[ "${INTENT_MODE:-}" == "headless" ]]; then
log "Refreshing JSON state for the Controller App..."
cmd_json_vars > /dev/null 2>&1 || true
if command -v am >/dev/null 2>&1; then
log "Returning control to Android App..."
sleep 1 # Brief visual pause before bouncing back
am start -n org.iiab.controller/org.iiab.controller.MainActivity >/dev/null 2>&1 || true
fi
fi
return $rc
}
### --- Pre-flight Check & Metrics ---
check_preflight_requirements() {
local outfd; outfd="$(console_outfd)"
printf "${BLU}[iiab] --- Pre-flight System Checks ---${RST}\n" >&"$outfd"
# 1. Architecture Check
local arch; arch=$(get_android_arch)
local arch_stat="${GRN}OK${RST}"
[[ "$arch" == "unknown" ]] && arch_stat="${YEL}WARN${RST}"
printf "${BLU}[iiab]${RST} * %-30s [%b]\n" "Architecture ($arch)" "$arch_stat" >&"$outfd"
# 2. Disk Space Logic (Thresholds: 2.5GB and 5GB)
local free_mb; free_mb=$(df -k "$PREFIX" | awk 'END{print $4 / 1024}' | cut -d. -f1)
local free_gb; free_gb=$(awk -v mb="$free_mb" 'BEGIN { printf "%.2f", mb / 1024 }')
local disk_stat="${GRN}OK${RST}"
if [[ "$free_mb" -lt 2500 ]]; then disk_stat="${RED}FAIL${RST}"; elif [[ "$free_mb" -lt 5000 ]]; then disk_stat="${YEL}WARN${RST}"; fi
printf "${BLU}[iiab]${RST} * %-30s [%b]\n" "Free Space (${free_gb} GB)" "$disk_stat" >&"$outfd"
# 3. Network Latency Check (Inside Table)
local net_stat="${RED}FAIL${RST}"
local net_text="Network Latency (Offline)"
local start_t; start_t=$(date +%s%N 2>/dev/null || echo 0)
if curl -Isf --connect-timeout 5 google.com >/dev/null 2>&1; then
local end_t; end_t=$(date +%s%N 2>/dev/null || echo 0)
if [[ "$start_t" != "0" && "$end_t" != "0" ]]; then
local delta=$(( (end_t - start_t) / 1000000 ))
net_text="Network Latency (${delta}ms)"
if [[ "$delta" -le 50 ]]; then net_stat="${BOLD}${BLU}EXCEL${RST}"
elif [[ "$delta" -le 150 ]]; then net_stat="${GRN}GOOD${RST}"
elif [[ "$delta" -le 250 ]]; then net_stat="${YEL}FAIR${RST}"
else net_stat="${RED}SLOW${RST}"
fi
fi
fi
printf "${BLU}[iiab]${RST} * %-30s [%b]\n" "$net_text" "$net_stat" >&"$outfd"
# 4. Developer Options Contextual Reminder
local sdk="${ANDROID_SDK:-0}"
local rel="${ANDROID_REL:-0}"
local dev_stat="${YEL}NOTE${RST}"
if [[ "$sdk" -ge 34 ]]; then
printf "${BLU}[iiab]${RST} * %-30s [%b]\n" "Dev. Options (Child Process)" "$dev_stat" >&"$outfd"
elif [[ "$sdk" -ge 31 ]]; then
printf "${BLU}[iiab]${RST} * %-30s [%b]\n" "Dev. Options (Phantom Process)" "$dev_stat" >&"$outfd"
else
printf "${BLU}[iiab]${RST} * %-30s [%b]\n" "Dev. Options (Not Required)" "${GRN}N/A${RST}" >&"$outfd"
fi
printf "${BLU}[iiab] --------------------------------------${RST}\n" >&"$outfd"
# --- Checks and warnings (summary) ---
[[ "$arch" == "unknown" ]] && warn "Unknown architecture. Results may vary."
if [[ "$free_mb" -lt 2500 ]]; then
warn_red "Error: Insufficient space to install IIAB on Android."
die "Please free up space (at least 2.5GB) to continue."
elif [[ "$free_mb" -lt 5000 ]]; then
log_yel "Warning: Limited storage detected (${free_gb} GB)."
warn "You may face limitations when adding additional content later."
tty_yesno_default_n "[iiab] Do you want to continue with a tight installation? [y/N]: " || die "Aborted by user."
else
ok "Sufficient disk space for installation (${free_gb} GB)"
log "Note: Space for multimedia content depends on the specific modules you add later."
fi
if [[ "$net_stat" == *FAIL* ]]; then
warn_red "Network unreachable or timeout. Downloads may fail."
elif [[ "$net_stat" == *SLOW* ]]; then
warn "High network latency detected."
fi
if [[ "$sdk" -ge 34 ]]; then
log_yel "Reminder: Developer Options must be enabled to toggle 'Disable child process restrictions'."
elif [[ "$sdk" -ge 31 ]]; then
log_yel "Reminder: Developer Options must be enabled to pair ADB and fix 'Phantom Process Killer'."
elif [[ "$sdk" -gt 0 && "$sdk" -le 30 ]]; then
ok "No known process restrictions for Android $rel."
fi
ok "Pre-flight checks completed."
countdown_timer 7 "\r${BLU}[iiab]${RST} Proceeding in %d seconds... "
}
welcome_interactive() {
local mode_label="${1:-Installation}"
local prompt_text="Press [ENTER] to start system validation... "
[[ "$mode_label" == "Preview" ]] && prompt_text="Press [ENTER] to exit welcome message... "
local outfd; outfd="$(console_outfd)"
{
clear
printf "${BLU}==================================================${RST}\n"
printf " 🌐 WELCOME TO IIAB on Android 🌐\n"
printf " Starting mode: ${mode_label}\n"
printf "${BLU}==================================================${RST}\n"
printf "\n${BOLD}Internet-in-a-Box (IIAB) on Android${RST} will allow\n"
printf "millions of people worldwide to build their own \n"
printf "family libraries, inside their own phones!\n"
blank
printf "This script prepares your Android device as an\n"
printf "Offline Learning Environment (Internet-in-a-Box).\n"
blank
printf "Please follow the installation guide at:\n"
printf "${YEL}*${RST} 📄: ${BLU}https://github.com/iiab/iiab-android${RST}\n"
blank
printf "Other online resources:\n"
printf "${YEL}*${RST} 🔗: ${BOLD}https://internet-in-a-box.org${RST}\n"
printf "${YEL}*${RST} 🐛: ${BOLD}https://github.com/iiab/iiab-android/issues${RST}\n"
blank
printf " TIP: Keep the charger around and ensure Termux\n"
printf " battery settings are set to 'Unrestricted'.\n"
printf "${BLU}==================================================${RST}\n"
if [[ -r /dev/tty ]]; then
printf "%s" "$prompt_text"
fi
} >&"$outfd"
if [[ -r /dev/tty ]]; then
read -r _ < /dev/tty || true
fi
}
offer_welcome_once() {
local mode_label="$1"
local stamp="${STATE_DIR}/stamp.welcome"
if [[ ! -f "$stamp" ]]; then
welcome_interactive "$mode_label"
date > "$stamp" 2>/dev/null || true
fi
}
measure_disk_usage() {
# $1 = Function or mode name to execute
local before; before=$(du -sm "$PREFIX/.." | awk '{print $1}')
log "Calculating installation footprint..."
# Execute the passed logic
"$@"
local after; after=$(du -sm "$PREFIX/.." | awk '{print $1}')
local footprint=$((after - before))
ok "Installation completed. System footprint: +${footprint}MB."
}
# -------------------------
# Help / usage (static text)
# -------------------------
usage() {
printf '%b\n' "
${BOLD}Usage:${RST} iiab-termux [MODE] [OPTIONS]
${BLU}=== CORE & INSTALL ===${RST}
${GRN}(no args)${RST} Baseline + IIAB Debian bootstrap
${GRN}--all${RST} Full setup: baseline, Debian, ADB, PPK, & checks
${GRN}--barebones${RST} Minimal installation: Termux base + proxy (no rootfs)
${GRN}--start, --login${RST} Start / Login IIAB Debian
${GRN}--iiab-android${RST} Install/update 'iiab-android' tool inside proot
${GRN}--install-module [M]${RST} Install a specific Ansible role (e.g. books)
${GRN}--json-vars${RST} Export local_vars.yml status as JSON (for Controller App)
${BLU}=== ADB & SYSTEM TUNING ===${RST}
${GRN}--with-adb${RST} Baseline + Debian + ADB wireless pair/connect
${GRN}--adb-only${RST} Only ADB pair/connect (skips Debian)
${GRN}--connect-only${RST} Connect to an already-paired device
${GRN}--ppk-only${RST} Set max_phantom_processes=256 via ADB
${GRN}--check${RST} Check Android readiness (Process restrictions, PPK)
${BLU}=== BACKUP & RESTORE ===${RST}
${GRN}--backup-rootfs${RST} Backup IIAB Debian to .tar.gz
${GRN}--restore-rootfs${RST} Restore IIAB Debian from local .tar.gz
${GRN}--pull-rootfs${RST} Download & restore rootfs from URL (P2P enabled)
${GRN}--remove-rootfs${RST} Delete IIAB Debian rootfs and all data
${BLU}=== PROXY (BOXYPROXY) ===${RST}
${GRN}--proxy-start${RST} Start background proxy
${GRN}--proxy-stop${RST} Stop background proxy
${GRN}--proxy-status${RST} Show proxy status
${BOLD}Options:${RST}
--connect-port [P] Skip CONNECT PORT prompt
--timeout [SECS] Wait time per prompt (default 180)
--no-meta4 Disable Metalink/P2P for --pull-rootfs
--keep-tarball Keep the downloaded archive after --pull-rootfs
--reset-iiab Reinstall IIAB Debian
--install-self Install the current script to Termux bin path
--welcome Show the welcome screen
--debug Enable extra logs
--help, --version Show this help or version
${YEL}Notes:${RST} Setup on Android 12 & 13 requires ADB due to OS design. 14+ simplifies this with system UI toggles
"
}
# ---- END 00_lib_common.sh ----
# ---- BEGIN 10_mod_logging.sh ----
# shellcheck shell=bash
# Module file (no shebang). Bundled by build_bundle.sh
# -------------------------
# Logging
# -------------------------
LOG_ENABLED=1
LOG_FILE="" # if empty, auto-generate under $LOG_DIR
LOG_KEEP=5 # keep only the last 5 days worth of logs
prune_old_logs() {
[[ -d "${LOG_DIR:-}" ]] || return 0
local keep="${LOG_KEEP:-3}"
local i=0 f
while IFS= read -r f; do
[[ -n "${f:-}" ]] || continue
i=$((i + 1))
(( i <= keep )) && continue
rm -f -- "$f" 2>/dev/null || true
done < <(ls -1t "$LOG_DIR"/*.log 2>/dev/null || true)
}
setup_logging() {
# Save original console fds so interactive tools still work after we redirect stdout/stderr.
exec 3>&1 4>&2
# If logging is disabled, still allow --debug to trace to console.
if [[ "${LOG_ENABLED:-1}" -ne 1 ]]; then
if [[ "${DEBUG:-0}" -eq 1 ]]; then
set -x
ok "Debug trace enabled (bash -x) -> console (logging disabled)"
fi
return 0
fi
mkdir -p "$LOG_DIR"
if [[ -z "${LOG_FILE:-}" ]]; then
LOG_FILE="${LOG_DIR}/iiab-termux.$(date +%Y%m%d).log"
else
mkdir -p "$(dirname -- "$LOG_FILE")"
fi
# Header (best-effort)
local started
started="$(date -Is 2>/dev/null || date 2>/dev/null || echo "?")"
{
echo "=== iiab termux setup log ==="
echo "Started: $started"
echo "Script: $0"
echo "Args: ${*:-}"
echo "Android SDK=${ANDROID_SDK:-?} Release=${ANDROID_REL:-?}"
echo "PWD: $(pwd 2>/dev/null || true)"
echo "================================"
} >>"$LOG_FILE" 2>/dev/null || true
chmod 600 "$LOG_FILE"
prune_old_logs
# Duplicate stdout/stderr to console + log (strip ANSI in log)
# Single pipeline for stable ordering (no stdout/stderr interleaving) at FD3.
exec > >(tee >(sed -E 's/\x1B\[[0-9;]*[ -/]*[@-~]//g' >>"$LOG_FILE") >&3) 2>&1
ok "Logging to: ${LOG_FILE/#$HOME/\~}"
# If --debug, send xtrace only to log
if [[ "${DEBUG:-0}" -eq 1 ]]; then
exec 9>>"$LOG_FILE"
export BASH_XTRACEFD=9
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
set -x
ok "Debug trace enabled (bash -x) -> log only"
fi
}
# ---- END 10_mod_logging.sh ----
# ---- BEGIN 15_mod_prepatch_env.sh ----
# shellcheck shell=bash
# Module file (no shebang). Bundled by build_bundle.sh
# -------------------------
# Environment Pre-patches & Hacks (15_mod_prepatch_env.sh)
# -------------------------
# This module acts as a registry for upstream bugs, weird Android
# edge cases, and environment quirks.
#
# ALL functions must be idempotent and fail silently if not needed.
python_patch_sysconfig_armv8l() {
# Fixes a bug in Termux Python 3.13 where 'armv8l' architecture throws a KeyError
# during pip C-extensions compilation (like aiohttp or zeroconf).
local py=""
py="$(command -v python 2>/dev/null || command -v python3 2>/dev/null || true)"
[[ -n "$py" ]] || return 0 # no python; end.
local sysconfig_file=""
sysconfig_file="$("$py" -c "import sysconfig; print(sysconfig.__file__)" 2>/dev/null || true)"
[[ -z "$sysconfig_file" ]] || [[ ! -f "$sysconfig_file" ]] && return 0
if grep -q '"armv8l": "armeabi_v7a"' "$sysconfig_file"; then
return 0 # already fixed; end.
fi
if grep -q '"armv7l": "armeabi_v7a"' "$sysconfig_file"; then
log_yel "Patching Python sysconfig to resolve armv8l architecture bug..."
sed -i 's/"armv7l": "armeabi_v7a",/"armv7l": "armeabi_v7a",\n "armv8l": "armeabi_v7a",/g' "$sysconfig_file"
fi
}
# ---- END 15_mod_prepatch_env.sh ----
# ---- BEGIN 20_mod_termux_base.sh ----
# shellcheck shell=bash
# Module file (no shebang). Bundled by build_bundle.sh
# -------------------------
# Python helpers + mDNS deps (zeroconf)
# -------------------------
# Rationale: If mDNS autodetect is enabled, prepare it here so it's available from the start.
TERMUX_ZEROCONF_STAMP="${STATE_DIR}/stamp.termux_zeroconf"
# Cache: avoid repeating zeroconf checks/installs/warnings in the same run.
PY_ZEROCONF_CHECKED=0
PY_ZEROCONF_OK=0
# -------------------------
# Python deps for boxyproxy (aiohttp)
# -------------------------
# Prepare it early so proxy-start works reliably.
TERMUX_AIOHTTP_STAMP="${STATE_DIR}/stamp.termux_aiohttp"
# Cache: avoid repeating aiohttp checks/installs/warnings in the same run.
PY_AIOHTTP_CHECKED=0
PY_AIOHTTP_OK=0
# Allow disabling auto-install (keep default enabled).
BOXYPROXY_DEPS_INSTALL="${BOXYPROXY_DEPS_INSTALL:-1}"
BOXYPROXY_DEPS_PIP_INSTALL="${BOXYPROXY_DEPS_PIP_INSTALL:-1}"
python_cmd() {
command -v python 2>/dev/null || command -v python3 2>/dev/null || true
}
python_has_zeroconf() {
local py=""
py="$(python_cmd)"
[[ -n "$py" ]] || return 1
"$py" -c 'import zeroconf' >/dev/null 2>&1
}
python_has_aiohttp() {
local py=""
py="$(python_cmd)"
[[ -n "$py" ]] || return 1
"$py" -c 'import aiohttp' >/dev/null 2>&1
}
python_pip_install_zeroconf() {
local py=""
py="$(python_cmd)"
[[ -n "$py" ]] || return 1
# Some environments may lack pip initially; try ensurepip if available.
if ! "$py" -m pip --version >/dev/null 2>&1; then
if "$py" -c 'import ensurepip' >/dev/null 2>&1; then
"$py" -m ensurepip --upgrade || return 1
"$py" -m pip --version || return 1
else
return 1
fi
fi
# Run pip directly on the real TTY when FD 3/4 are available.
if : >&3 2>/dev/null && : >&4 2>/dev/null; then
( exec 1>&3 2>&4; "$py" -m pip install --upgrade zeroconf --progress-bar on )
else
"$py" -m pip install --upgrade zeroconf --progress-bar on
fi
}
python_ensure_zeroconf() {
# Fast path: if we already decided in this run, return the same result.
if [[ "${PY_ZEROCONF_CHECKED:-0}" -eq 1 ]]; then
[[ "${PY_ZEROCONF_OK:-0}" -eq 1 ]] && return 0
return 1
fi
PY_ZEROCONF_CHECKED=1
# Android < 11 does not use Wireless debugging pairing; skip mDNS prep.
if [[ "${ANDROID_SDK:-}" =~ ^[0-9]+$ ]] && (( ANDROID_SDK < 30 )); then
PY_ZEROCONF_OK=0
return 1
fi
if python_has_zeroconf; then
PY_ZEROCONF_OK=1
return 0
fi
[[ "${ADB_MDNS_PIP_INSTALL:-1}" -eq 1 ]] || { PY_ZEROCONF_OK=0; return 1; }
log_yel "Python module 'zeroconf' not found. Installing it..."
if python_pip_install_zeroconf && python_has_zeroconf; then
ok "Installed Python module 'zeroconf' (mDNS autodetect enabled)."
PY_ZEROCONF_OK=1
return 0
fi
warn "Could not install 'zeroconf' (no network, pip missing, or install failed). Falling back to manual prompts."
PY_ZEROCONF_OK=0
return 1
}
python_pip_install_aiohttp() {
local py=""
py="$(python_cmd)"
[[ -n "$py" ]] || return 1
if ! "$py" -m pip --version >/dev/null 2>&1; then
if "$py" -c 'import ensurepip' >/dev/null 2>&1; then
"$py" -m ensurepip --upgrade || return 1
"$py" -m pip --version || return 1
else
return 1
fi
fi
if : >&3 2>/dev/null && : >&4 2>/dev/null; then
( exec 1>&3 2>&4; "$py" -m pip install --upgrade aiohttp --progress-bar on )
else
"$py" -m pip install --upgrade aiohttp --progress-bar on
fi
}
termux_prepare_boxyproxy_deps() {
have python || have python3 || return 0
python_has_aiohttp && return 0
log_yel "Python module 'aiohttp' not found. Installing it ..."
python_pip_install_aiohttp >/dev/null 2>&1 || true
python_has_aiohttp && { ok "Installed 'aiohttp' via pip."; return 0; }
warn "Could not install 'aiohttp'. boxyproxy may fail until it's installed."
return 1
}
termux_prepare_mdns_deps() {
# Only if mDNS autodetect is enabled & pip-install is allowed.
[[ "${ADB_MDNS:-0}" -eq 1 ]] || return 0
[[ "${ADB_MDNS_PIP_INSTALL:-1}" -eq 1 ]] || return 0
have python || have python3 || return 0
# If we stamped success before and it's still present, do nothing.
if [[ -f "$TERMUX_ZEROCONF_STAMP" ]] && python_has_zeroconf; then
return 0
fi
# If stamp exists but module disappeared, drop stamp and retry.
[[ -f "$TERMUX_ZEROCONF_STAMP" ]] && rm -f "$TERMUX_ZEROCONF_STAMP" >/dev/null 2>&1 || true
log "Preparing mDNS autodetect dependency (python module: zeroconf)..."
if python_ensure_zeroconf; then
date > "$TERMUX_ZEROCONF_STAMP" 2>/dev/null || true
else
# python_ensure_zeroconf already warned; keep this generic to avoid duplicates.
warn "mDNS autodetect may fall back to manual prompts."
fi
return 0
}
# If baseline fails, store the last command that failed for better diagnostics.
BASELINE_ERR=""
baseline_need_python() {
# Android 11+ (SDK 30+) only
[[ "${ANDROID_SDK:-}" =~ ^[0-9]+$ ]] && (( ANDROID_SDK >= 30 ))
}
baseline_prereqs_ok() {
have proot-distro && have adb && have termux-notification && have termux-dialog && have sha256sum || return 1
if baseline_need_python; then
have python || return 1
fi
return 0
}