Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
998 lines (891 loc) · 37.1 KB
/
Copy pathsetup.py
File metadata and controls
998 lines (891 loc) · 37.1 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
#!/usr/bin/env python3
"""
WatchROM — Dependency Installer & First-Run Setup
Installs all system packages, pip modules, and GitHub tools
"""
import os
import sys
import subprocess
import shutil
import json
import time
from pathlib import Path
# ── Colors (no rich yet — installs it) ────────────────────────────────────────
R = "\033[0;31m"; G = "\033[0;32m"; Y = "\033[1;33m"
C = "\033[0;36m"; M = "\033[0;35m"; B = "\033[0;34m"
W = "\033[1;37m"; DIM= "\033[2m"; NC = "\033[0m"
BOLD="\033[1m"
BANNER = f"""{C}
██╗ ██╗ █████╗ ████████╗ ██████╗██╗ ██╗██████╗ ██████╗ ███╗ ███╗
██║ ██║██╔══██╗╚══██╔══╝██╔════╝██║ ██║██╔══██╗██╔═══██╗████╗ ████║
██║ █╗ ██║███████║ ██║ ██║ ███████║██████╔╝██║ ██║██╔████╔██║
██║███╗██║██╔══██║ ██║ ██║ ██╔══██║██╔══██╗██║ ██║██║╚██╔╝██║
╚███╔███╔╝██║ ██║ ██║ ╚██████╗██║ ██║██║ ██║╚██████╔╝██║ ╚═╝ ██║
╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
{NC}{Y} ★ One Kit to Rule Them All ★ Dependency Installer & Setup{NC}
{DIM} MTK (MT6739/MT6761/MT6762/MT6765/MT6768/MT6771/MT6785/MT6789){NC}
{DIM} Unisoc (SC9832E/SC9863A/SL8541E/SC8541E/SC9863/UIS8581A){NC}
"""
TOOLKIT_ROOT = Path(__file__).resolve().parent
REPOS_DIR = TOOLKIT_ROOT.parent / "watchrom_repos" # Tools cloned by setup.py (Magisk, jadx, etc.)
VENDOR_DIR = TOOLKIT_ROOT / "vendor" # Vendored in-tree Python packages (mtkclient, edl, unpac)
STATUS_FILE = TOOLKIT_ROOT / ".setup_status.json"
def title(msg):
print(f"\n{BOLD}{C}{'─'*60}{NC}")
print(f"{BOLD}{W} {msg}{NC}")
print(f"{BOLD}{C}{'─'*60}{NC}")
def ok(msg): print(f" {G}✓{NC} {msg}")
def warn(msg): print(f" {Y}!{NC} {msg}")
def err(msg): print(f" {R}✗{NC} {msg}")
def info(msg): print(f" {DIM}{msg}{NC}")
def step(msg): print(f" {C}→{NC} {msg}", end=" ", flush=True)
def run(cmd, capture=True, timeout=300, cwd=None):
try:
result = subprocess.run(
cmd if isinstance(cmd, list) else cmd.split(),
capture_output=capture, text=True,
timeout=timeout, cwd=cwd
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return 1, "", "timeout"
except FileNotFoundError:
return 1, "", "not found"
except Exception as e:
return 1, "", str(e)
def load_status():
status = {}
if STATUS_FILE.exists():
try:
status = json.loads(STATUS_FILE.read_text())
except Exception:
pass
# Validate cloned repos actually exist — purge stale entries
cloned = status.get("cloned_repos", [])
valid = [name for name in cloned if (REPOS_DIR / name).exists()]
if len(valid) != len(cloned):
status["cloned_repos"] = valid
# Save immediately so stale status doesn't persist
save_status(status)
return status
def save_status(status):
STATUS_FILE.write_text(json.dumps(status, indent=2))
# ═══════════════════════════════════════════════════════════════════════════════
# DEPENDENCY DEFINITIONS
# ═══════════════════════════════════════════════════════════════════════════════
APT_PACKAGES = [
# Core Android tools — on Debian 13+, adb is in android-platform-tools-base (non-free)
# install.sh checks and warns if missing
"adb", "fastboot",
# Java (needed for apktool, signapk, jadx)
"default-jdk",
# Build essentials
"build-essential", "git", "wget", "curl", "unzip", "zip",
"autoconf", "automake", "libtool", "pkg-config",
# Python
"python3", "python3-pip", "python3-dev",
# Filesystem tools
"e2fsprogs", # ext4: debugfs, dumpe2fs, fsck.ext4
"erofs-utils", # erofs: fsck.erofs, mkfs.erofs
"f2fs-tools", # f2fs filesystem
"android-sdk-libsparse-utils", # simg2img, img2simg
# Device tree tools
"device-tree-compiler", # dtc, fdtput, fdtget
# Compression
"lz4", "zstd", "xz-utils",
# Crypto / signing
"openssl",
# Reverse engineering
"apktool",
# Network tools
"tcpdump", "net-tools",
# Misc utils
"xxd", "binutils", "file", "patchelf",
"libusb-1.0-0", "libusb-1.0-0-dev", "libudev-dev",
"udev", "dh-autoreconf",
# SELinux tools
"setools",
# mkbootimg / unpackbootimg
"mkbootimg",
# Rockchip tools — rkdeveloptool available in Debian bookworm+/Ubuntu
"rkdeveloptool",
# Allwinner / sunxi tools
"sunxi-tools",
# Filesystem tools (squashfs for Realtek rescue images)
"squashfs-tools",
# binwalk for unknown firmware analysis
"binwalk",
# Qualcomm / serial port tools
"minicom",
"screen",
"picocom",
# Additional signing tools — signapk is part of android-platform-build
"signapk",
]
# WARNING: Keep PIP_PACKAGES in sync with core/registry.py PINNED_DEPS["pip"].
# core/registry.py is the authoritative version-spec source for runtime validation.
PIP_PACKAGES = {
# ~= means compatible-release: allows patch bumps, blocks major/minor API breaks.
# protobuf stays >= (its version numbering is chaotic — 3→21→4→7+).
"rich": "~=13.0",
"click": "~=8.0",
"prompt_toolkit": "~=3.0",
"pyserial": "~=3.5",
"requests": "~=2.28",
"pycryptodome": "~=3.15",
"protobuf": ">=4.0.0",
"bsdiff4": "~=1.2",
}
# GitHub repos to clone into REPOS_DIR
# Format: (repo_url, clone_name, install_cmd_or_None, binary_to_link)
GITHUB_REPOS = [
{
"url": "https://github.com/bkerler/mtkclient",
"name": "mtkclient",
"desc": "MTK BROM exploit + full flash toolkit",
"install": "pip3 install --break-system-packages -e . 2>/dev/null || pip3 install -e .",
"bins": ["mtk"],
"chip": "MTK",
},
{
"url": "https://github.com/bkerler/edl",
"name": "edl",
"desc": "Qualcomm / Unisoc EDL protocol tool",
"install": "pip3 install --break-system-packages -r requirements.txt 2>/dev/null || true",
"bins": ["edl"],
"chip": "Unisoc/MTK",
},
{
"url": "https://github.com/topjohnwu/Magisk",
"name": "Magisk",
"desc": "Magisk root manager (source reference)",
"install": None,
"bins": [],
"chip": "Any",
},
{
"url": "https://github.com/skylot/jadx",
"name": "jadx",
"desc": "Java decompiler for APK analysis",
"install": "cd jadx && ./gradlew dist 2>/dev/null || true",
"bins": ["jadx/build/jadx/bin/jadx"],
"chip": "Any",
},
{
"url": "https://github.com/iBotPeaches/Apktool",
"name": "Apktool",
"desc": "APK decode/rebuild tool",
"install": None,
"bins": [],
"chip": "Any",
},
{
"url": "https://github.com/ssut/payload-dumper-go",
"name": "payload-dumper-go",
"desc": "OTA payload.bin extractor",
"install": "go build -o payload-dumper-go . 2>/dev/null || true",
"bins": ["payload-dumper-go"],
"chip": "Any",
},
{
"url": "https://github.com/cfig/Android_boot_image_editor",
"name": "bootimgtools",
"desc": "Boot image pack/unpack (Kotlin)",
"install": None,
"bins": [],
"chip": "Any",
},
{
"url": "https://github.com/unix3dgforce/OppoDecrypt",
"name": "OppoDecrypt",
"desc": "Decrypt Oppo/Realme/OnePlus firmware",
"install": "pip3 install --break-system-packages -r requirements.txt 2>/dev/null || true",
"bins": [],
"chip": "MTK",
},
{
"url": "https://github.com/bgcngm/mtk-tools",
"name": "mtk-tools-bgcngm",
"desc": "MTK boot.img/recovery.img unpack/repack Perl scripts",
"install": None,
"bins": [],
"chip": "MTK",
},
{
"url": "https://github.com/Iscle/unpac",
"name": "unpac",
"desc": "Unisoc PAC firmware unpacker (Python)",
"install": "pip3 install --break-system-packages -e . 2>/dev/null || pip3 install -e .",
"bins": ["unpac"],
"chip": "Unisoc",
},
{
"url": "https://github.com/WerWolv/ImHex",
"name": "ImHex",
"desc": "Hex editor with pattern matching",
"install": None,
"bins": [],
"chip": "Any",
},
{
"url": "https://github.com/RikkaApps/Shizuku",
"name": "Shizuku",
"desc": "Privileged API access framework",
"install": None,
"bins": [],
"chip": "Any",
},
{
"url": "https://github.com/google/android-emulator-container-scripts",
"name": "android-emulator",
"desc": "Android emulator container scripts",
"install": None,
"bins": [],
"chip": "Any",
},
# ── Rockchip tools ─────────────────────────────────────────────────────
{
"url": "https://github.com/rockchip-linux/rkdeveloptool",
"name": "rkdeveloptool",
"desc": "Rockchip MaskROM flash tool (Linux)",
"install": "dpkg -l rkdeveloptool >/dev/null 2>&1 && echo 'already-installed' || "
"(autoreconf -i 2>/dev/null && ./configure 2>/dev/null && make -j$(nproc) 2>/dev/null && "
"sudo cp rkdeveloptool /usr/local/bin/ 2>/dev/null) || true",
"bins": ["rkdeveloptool", "/usr/local/bin/rkdeveloptool"],
"chip": "Rockchip",
},
{
"url": "https://github.com/linux-rockchip/rkflashtool",
"name": "rkflashtool",
"desc": "Alternative Rockchip flash tool",
"install": "make 2>/dev/null || true",
"bins": ["rkflashtool"],
"chip": "Rockchip",
},
{
"url": "https://github.com/rockchip-linux/u-boot",
"name": "rk-uboot",
"desc": "Rockchip U-Boot source (loaders)",
"install": None,
"bins": [],
"chip": "Rockchip",
},
# ── Allwinner tools ────────────────────────────────────────────────────
{
"url": "https://github.com/linux-sunxi/sunxi-tools",
"name": "sunxi-tools",
"desc": "Allwinner FEL/flash tools (sunxi-fel, sunxi-nand-image-builder)",
"install": "make 2>/dev/null || true",
"bins": ["sunxi-fel","sunxi-nand-image-builder","sunxi-fexc"],
"chip": "Allwinner",
},
{
"url": "https://github.com/linux-sunxi/u-boot-sunxi",
"name": "u-boot-sunxi",
"desc": "Allwinner U-Boot (SPL loaders for FEL)",
"install": None,
"bins": [],
"chip": "Allwinner",
},
{
"url": "https://github.com/allwinner-zh/bootloader",
"name": "aw-bootloader",
"desc": "Allwinner boot0/boot1 sources",
"install": None,
"bins": [],
"chip": "Allwinner",
},
{
"url": "https://github.com/Ithamar/awutils",
"name": "awutils",
"desc": "Allwinner firmware image utilities",
"install": "make 2>/dev/null || true",
"bins": [],
"chip": "Allwinner",
},
# ── Realtek tools ──────────────────────────────────────────────────────
# NOTE: jrior001/rtd-flash (the original RTD1xxx USB flash tool) was removed
# from GitHub. Realtek RTD devices use U-Boot USB rescue recovery.
# See: Realtek VendorInterface.flash_instructions() for details.
# ── Qualcomm / Snapdragon tools ────────────────────────────────────────
{
"url": "https://github.com/bkerler/edl",
"name": "edl",
"desc": "Qualcomm EDL 9008 protocol tool — EFS backup, partition ops",
"install": "pip3 install --break-system-packages -r requirements.txt 2>/dev/null || true",
"bins": ["edl"],
"chip": "Qualcomm",
},
{
"url": "https://github.com/NationalSecurityAgency/ghidra",
"name": "ghidra",
"desc": "Reverse engineering suite (modem firmware analysis)",
"install": None,
"bins": [],
"chip": "Any",
},
{
"url": "https://github.com/openpst/openpst",
"name": "openpst",
"desc": "Open source QPST alternative — EFS read/write, NV items",
"install": None,
"bins": [],
"chip": "Qualcomm",
},
{
"url": "https://github.com/forth32/qtools",
"name": "qtools",
"desc": "Qualcomm flash modem tools (qcommand, qrflash, qwflash, qdload)",
"install": "make 2>/dev/null || true",
"bins": ["qcommand","qrflash","qwflash","qdload"],
"chip": "Qualcomm",
},
{
"url": "https://github.com/JohnBel/EfsTools",
"name": "EfsTools",
"desc": "Cross-platform Qualcomm EFS explorer (.NET)",
"install": None,
"bins": [],
"chip": "Qualcomm",
},
]
# Standalone binary downloads
BINARY_DOWNLOADS = [
{
"name": "apktool",
"url": "https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool",
"jar_url": "https://github.com/iBotPeaches/Apktool/releases/download/v2.9.3/apktool_2.9.3.jar",
"dest": "/usr/local/bin/apktool",
"jar_dest":"/usr/local/lib/apktool.jar",
"wrapper": True,
},
{
"name": "jadx",
"url": "https://github.com/skylot/jadx/releases/download/v1.5.0/jadx-1.5.0.zip",
"dest": "/opt/jadx",
"zip": True,
"bin_src": "/opt/jadx/bin/jadx",
"bin_dst": "/usr/local/bin/jadx",
},
]
# udev rules for MTK + Unisoc + generic Android
UDEV_RULES = """\
# WatchROM — Android Device USB Rules
# MediaTek
SUBSYSTEM=="usb", ATTR{idVendor}=="0e8d", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Unisoc / Spreadtrum
SUBSYSTEM=="usb", ATTR{idVendor}=="1782", MODE="0666", GROUP="plugdev", TAG+="uaccess"
SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Google ADB/Fastboot
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Qualcomm EDL
SUBSYSTEM=="usb", ATTR{idVendor}=="05c6", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Xiaomi
SUBSYSTEM=="usb", ATTR{idVendor}=="2717", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Samsung
SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# OnePlus
SUBSYSTEM=="usb", ATTR{idVendor}=="2a70", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Huawei
SUBSYSTEM=="usb", ATTR{idVendor}=="12d1", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# LG
SUBSYSTEM=="usb", ATTR{idVendor}=="1004", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# HTC
SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Motorola
SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Sony
SUBSYSTEM=="usb", ATTR{idVendor}=="0fce", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# OPPO / Realme
SUBSYSTEM=="usb", ATTR{idVendor}=="22d9", MODE="0666", GROUP="plugdev", TAG+="uaccess"
# Vivo
SUBSYSTEM=="usb", ATTR{idVendor}=="2d95", MODE="0666", GROUP="plugdev", TAG+="uaccess"
"""
# ═══════════════════════════════════════════════════════════════════════════════
# INSTALL FUNCTIONS
# ═══════════════════════════════════════════════════════════════════════════════
def install_apt_packages(status: dict) -> dict:
title("System Packages (apt)")
if status.get("apt_done"):
ok("apt packages already installed — skipping")
return status
step("Updating apt cache...")
rc, _, _ = run(["sudo", "apt-get", "update", "-qq"], timeout=120)
print(f"{G}OK{NC}" if rc == 0 else f"{Y}warn{NC}")
failed = []
for pkg in APT_PACKAGES:
step(f"Installing {pkg}...")
rc, _, err = run(
["sudo", "apt-get", "install", "-y", "-qq", pkg],
timeout=120
)
if rc == 0:
print(f"{G}✓{NC}")
else:
print(f"{Y}skip{NC}")
failed.append(pkg)
info(f" (may be unavailable on this distro)")
if failed:
warn(f"Could not install via apt: {', '.join(failed)}")
else:
ok("All apt packages installed")
status["apt_done"] = True
return status
def install_pip_packages(status: dict) -> dict:
title("Python Packages (pip)")
if status.get("pip_done"):
ok("pip packages already installed — skipping")
return status
for pkg, version in PIP_PACKAGES.items():
spec = f"{pkg}{version}"
step(f"pip install {spec}...")
rc, _, _ = run(
[sys.executable, "-m", "pip", "install", "--break-system-packages",
"-q", spec],
timeout=120
)
if rc != 0:
# Try without --break-system-packages
rc, _, _ = run(
[sys.executable, "-m", "pip", "install", "-q", spec],
timeout=120
)
print(f"{G}✓{NC}" if rc == 0 else f"{Y}skip{NC}")
status["pip_done"] = True
return status
def install_binary_tools(status: dict) -> dict:
title("Standalone Binary Tools")
# apktool
if not shutil.which("apktool"):
step("Installing apktool...")
try:
import urllib.request
jar_path = Path("/usr/local/lib/apktool.jar")
wrap_path = Path("/usr/local/bin/apktool")
urllib.request.urlretrieve(
"https://github.com/iBotPeaches/Apktool/releases/download/v2.9.3/apktool_2.9.3.jar",
str(jar_path)
)
wrap_path.write_text(
"#!/bin/bash\nexec java -jar /usr/local/lib/apktool.jar \"$@\"\n"
)
os.chmod(wrap_path, 0o755)
print(f"{G}✓{NC}")
except Exception as e:
print(f"{Y}skip ({e}){NC}")
else:
ok(f"apktool already available: {shutil.which('apktool')}")
# jadx
if not shutil.which("jadx"):
step("Installing jadx 1.5.0...")
try:
import urllib.request, zipfile, io
url = "https://github.com/skylot/jadx/releases/download/v1.5.0/jadx-1.5.0.zip"
dest = Path("/opt/jadx")
dest.mkdir(parents=True, exist_ok=True)
data = urllib.request.urlopen(url, timeout=60).read()
with zipfile.ZipFile(io.BytesIO(data)) as z:
z.extractall(str(dest))
jadx_bin = dest / "bin" / "jadx"
if jadx_bin.exists():
os.chmod(jadx_bin, 0o755)
link = Path("/usr/local/bin/jadx")
if link.exists(): link.unlink()
link.symlink_to(jadx_bin)
print(f"{G}✓{NC}")
else:
print(f"{Y}skip (bin not found in zip){NC}")
except Exception as e:
print(f"{Y}skip ({e}){NC}")
else:
ok(f"jadx already available")
# avbtool (vendored in-tree from AOSP external/avb)
if not shutil.which("avbtool"):
avb_vendored = TOOLKIT_ROOT / "tools" / "avbtool.py"
if avb_vendored.exists():
step("Linking vendored avbtool...")
try:
link = Path("/usr/local/bin/avbtool")
if link.exists() or link.is_symlink():
link.unlink()
os.chmod(avb_vendored, 0o755)
link.symlink_to(avb_vendored.resolve())
print(f"{G}✓{NC}")
except Exception as e:
print(f"{Y}skip ({e}){NC}")
else:
print(f"{Y}skip (tools/avbtool.py not found){NC}")
else:
ok(f"avbtool already available")
# zipalign (from android build tools)
if not shutil.which("zipalign"):
step("Looking for zipalign in SDK paths...")
sdk_root = os.environ.get("ANDROID_HOME",
os.path.expanduser("~/Android/Sdk"))
found = list(Path(sdk_root).glob("build-tools/*/zipalign")) if Path(sdk_root).exists() else []
if found:
os.chmod(found[-1], 0o755)
link = Path("/usr/local/bin/zipalign")
if not link.exists():
link.symlink_to(found[-1])
print(f"{G}✓{NC}")
else:
print(f"{DIM}not found in SDK{NC}")
# apksigner
if not shutil.which("apksigner"):
sdk_root = os.environ.get("ANDROID_HOME",
os.path.expanduser("~/Android/Sdk"))
found = list(Path(sdk_root).glob("build-tools/*/apksigner")) if Path(sdk_root).exists() else []
if found:
link = Path("/usr/local/bin/apksigner")
if not link.exists():
link.symlink_to(found[-1])
ok("apksigner linked from SDK")
return status
def clone_github_repos(status: dict) -> dict:
title(f"GitHub Repositories → {REPOS_DIR}")
REPOS_DIR.mkdir(parents=True, exist_ok=True)
cloned = status.get("cloned_repos", [])
for repo in GITHUB_REPOS:
name = repo["name"]
url = repo["url"]
desc = repo["desc"]
dest = REPOS_DIR / name
install = repo.get("install")
bins = repo.get("bins", [])
step(f"[{repo['chip']}] {name} — {desc}...")
if name in cloned and dest.exists():
print(f"{DIM}already cloned{NC}")
continue
# Determine clone strategy: pinned tag > pinned commit > latest
from core.registry import PINNED_DEPS
pin = PINNED_DEPS.get("git", {}).get(name, {})
tag = pin.get("tag")
commit = pin.get("commit")
if tag:
clone_cmd = ["git", "clone", "--depth=1", "--quiet",
"--branch", tag, url, str(dest)]
else:
clone_cmd = ["git", "clone", "--depth=1", "--quiet", url, str(dest)]
rc, _, err = run(clone_cmd, timeout=180)
# If tag clone failed, fall back to latest
if rc != 0 and tag:
rc, _, err = run(
["git", "clone", "--depth=1", "--quiet", url, str(dest)],
timeout=180
)
# Checkout specific commit if pinned
if rc == 0 and commit and dest.exists():
run(["git", "-C", str(dest), "checkout", commit, "--quiet"],
check=False, timeout=30)
if rc != 0:
if dest.exists() and any(dest.iterdir()):
print(f"{DIM}already exists{NC}")
else:
print(f"{Y}failed — offline?{NC}")
continue
print(f"{G}✓ cloned{NC}")
cloned.append(name)
# Run install command
if install:
step(f" Installing {name} dependencies...")
rc2, _, _ = run(
install, capture=True, timeout=300, cwd=str(dest)
)
print(f"{G}OK{NC}" if rc2 == 0 else f"{Y}partial{NC}")
# Link binaries
for bin_rel in bins:
bin_path = dest / bin_rel if not bin_rel.startswith("/") else Path(bin_rel)
if bin_path.exists():
link_name = bin_path.name
link_dest = Path("/usr/local/bin") / link_name
try:
if link_dest.exists() or link_dest.is_symlink():
link_dest.unlink()
link_dest.symlink_to(bin_path.resolve())
os.chmod(bin_path, 0o755)
info(f" → linked {link_name} to /usr/local/bin/")
except Exception:
pass
status["cloned_repos"] = cloned
return status
def setup_udev(status: dict) -> dict:
title("udev Rules (USB device permissions)")
if status.get("udev_done"):
ok("udev rules already installed")
return status
rules_path = Path("/etc/udev/rules.d/99-watchrom.rules")
try:
tmp = Path("/tmp/watchrom_udev.rules")
tmp.write_text(UDEV_RULES)
rc, _, _ = run(["sudo", "cp", str(tmp), str(rules_path)])
if rc == 0:
run(["sudo", "udevadm", "control", "--reload-rules"])
run(["sudo", "udevadm", "trigger"])
# Add current user to plugdev group
user = os.environ.get("USER", os.environ.get("USERNAME", ""))
if user:
run(["sudo", "usermod", "-aG", "plugdev", user])
ok(f"udev rules installed → {rules_path}")
ok("User added to plugdev group (re-login may be needed)")
else:
warn("Could not write udev rules (no sudo?)")
except Exception as e:
warn(f"udev setup: {e}")
status["udev_done"] = True
return status
def install_watchrom_cli(status: dict) -> dict:
title("WatchROM CLI Registration")
launcher = Path("/usr/local/bin/watchrom")
main_py = TOOLKIT_ROOT / "main.py"
script = (
"#!/usr/bin/env bash\n"
f"exec {sys.executable} {main_py} \"$@\"\n"
)
try:
tmp = Path("/tmp/watchrom_launcher")
tmp.write_text(script)
os.chmod(tmp, 0o755)
rc, _, _ = run(["sudo", "cp", str(tmp), str(launcher)])
if rc == 0:
ok(f"watchrom CLI → {launcher}")
else:
# Try without sudo (user bin)
user_bin = Path.home() / ".local/bin"
user_bin.mkdir(parents=True, exist_ok=True)
(user_bin / "watchrom").write_text(script)
os.chmod(user_bin / "watchrom", 0o755)
ok(f"watchrom CLI → {user_bin}/watchrom")
except Exception as e:
warn(f"CLI registration: {e}")
# Also make main.py itself executable
try:
os.chmod(main_py, 0o755)
except Exception:
pass
status["cli_done"] = True
return status
def verify_tools() -> dict:
title("Tool Availability Check")
tools = {
"adb": ("Android Debug Bridge", "sudo apt install adb"),
"fastboot": ("Android Fastboot", "sudo apt install fastboot"),
"java": ("Java Runtime", "sudo apt install default-jdk"),
"apktool": ("APK decode/rebuild", "watchrom installs this"),
"jadx": ("Java decompiler", "watchrom installs this"),
"dtc": ("Device tree compiler", "sudo apt install device-tree-compiler"),
"openssl": ("Crypto / key generation", "sudo apt install openssl"),
"simg2img": ("Sparse image converter", "sudo apt install android-sdk-libsparse-utils"),
"debugfs": ("ext4 inspection", "sudo apt install e2fsprogs"),
"git": ("Version control", "sudo apt install git"),
# avbtool checked via vendored path below (not via shutil.which)
"mkbootimg": ("Boot image builder", "sudo apt install mkbootimg"),
"python3": ("Python 3", "sudo apt install python3"),
}
results = {}
for tool, (desc, hint) in tools.items():
path = shutil.which(tool)
if path:
ok(f"{tool:16s} {DIM}{desc}{NC}")
results[tool] = True
else:
warn(f"{tool:16s} {DIM}NOT FOUND — {hint}{NC}")
results[tool] = False
# mtkclient check (vendored or cloned)
mtk_vendored = VENDOR_DIR / "mtkclient" / "mtk"
mtk_cloned = REPOS_DIR / "mtkclient" / "mtk"
if mtk_vendored.exists() or mtk_cloned.exists() or shutil.which("mtk"):
src = "vendor" if mtk_vendored.exists() else "watchrom_repos"
ok(f"{'mtkclient':16s} {DIM}MTK BROM tool ({src}){NC}")
results["mtkclient"] = True
else:
warn(f"{'mtkclient':16s} {DIM}Not available (run vendor/clone.sh or setup.py){NC}")
results["mtkclient"] = False
# edl check (vendored or cloned)
edl_vendored = VENDOR_DIR / "edl" / "edl.py"
edl_cloned = REPOS_DIR / "edl" / "edl.py"
edl_which = shutil.which("edl")
if edl_vendored.exists() or edl_cloned.exists() or edl_which:
src = "vendor" if edl_vendored.exists() else ("watchrom_repos" if edl_cloned.exists() else "PATH")
ok(f"{'edl':16s} {DIM}Qualcomm/Unisoc EDL tool ({src}){NC}")
results["edl"] = True
else:
warn(f"{'edl':16s} {DIM}Not available (run vendor/clone.sh or setup.py){NC}")
results["edl"] = False
# unpac check (vendored or cloned)
unpac_vendored = VENDOR_DIR / "unpac" / "main.py"
unpac_cloned = REPOS_DIR / "unpac" / "main.py"
unpac_which = shutil.which("unpac")
if unpac_vendored.exists() or unpac_cloned.exists() or unpac_which:
src = "vendor" if unpac_vendored.exists() else ("watchrom_repos" if unpac_cloned.exists() else "PATH")
ok(f"{'unpac':16s} {DIM}Unisoc PAC unpacker ({src}){NC}")
results["unpac"] = True
else:
warn(f"{'unpac':16s} {DIM}Not available (run vendor/clone.sh or setup.py){NC}")
results["unpac"] = False
# avbtool check (vendored in-tree)
avb_vendored = TOOLKIT_ROOT / "tools" / "avbtool.py"
avb_which = shutil.which("avbtool")
if avb_vendored.exists() or avb_which:
src = "tools/avbtool.py" if avb_vendored.exists() else "PATH"
ok(f"{'avbtool':16s} {DIM}AVB signing tool ({src}){NC}")
results["avbtool"] = True
else:
warn(f"{'avbtool':16s} {DIM}missing (run setup.py to link vendored copy){NC}")
results["avbtool"] = False
return results
def print_summary(tool_status: dict, status: dict):
title("Setup Complete")
ready = sum(1 for v in tool_status.values() if v)
not_ready= sum(1 for v in tool_status.values() if not v)
cloned = len(status.get("cloned_repos", []))
print(f"\n {G}Tools ready : {ready}{NC}")
if not_ready:
print(f" {Y}Tools missing: {not_ready} (optional — core functions still work){NC}")
print(f" {C}GitHub repos : {cloned} cloned → {REPOS_DIR}{NC}")
print(f"""
{BOLD}{G}╔══════════════════════════════════════════════════╗{NC}
{BOLD}{G}║ WatchROM is ready! ║{NC}
{BOLD}{G}║ ║{NC}
{BOLD}{G}║ Run: watchrom ║{NC}
{BOLD}{G}║ OR: python3 {str(TOOLKIT_ROOT)}/launcher.py ║{NC}
{BOLD}{G}╚══════════════════════════════════════════════════╝{NC}
{DIM}Connect your device and run: watchrom{NC}
{DIM}The tool will auto-scan and offer to backup before anything else.{NC}
""")
def show_plan():
"""Print what would be installed without doing it (--dry-run)."""
title("Install Plan (dry-run)")
print(f" System packages (apt): {len(APT_PACKAGES)} packages")
print(f" Python packages (pip): {len(PIP_PACKAGES)} packages")
print(f" Binary tools: apktool, jadx, avbtool, zipalign, apksigner")
print(f" GitHub repos: {len(GITHUB_REPOS)} repos → {REPOS_DIR}")
print(f" udev rules: /etc/udev/rules.d/99-watchrom.rules")
print(f" CLI wrappers: /usr/local/bin/watchrom")
print(f" Status file: {STATUS_FILE}\n")
print(f" {DIM}Run without --dry-run to execute.{NC}\n")
def uninstall():
"""Remove all WatchROM installed artifacts."""
title("Uninstall WatchROM")
removed = 0
# CLI wrappers
for path in ["/usr/local/bin/watchrom", "/usr/local/bin/watchrom-menu"]:
p = Path(path)
if p.exists() or p.is_symlink():
step(f"Removing {path}...")
try:
p.unlink()
print(f"{G}✓{NC}")
removed += 1
except Exception as e:
print(f"{Y}skip ({e}){NC}")
# User-local CLI wrapper
user_local = Path.home() / ".local/bin/watchrom"
if user_local.exists():
step(f"Removing {user_local}...")
try:
user_local.unlink()
print(f"{G}✓{NC}")
removed += 1
except Exception as e:
print(f"{Y}skip ({e}){NC}")
# udev rules
udev_path = Path("/etc/udev/rules.d/99-watchrom.rules")
if udev_path.exists():
step("Removing udev rules...")
try:
run(["sudo", "rm", "-f", str(udev_path)])
run(["sudo", "udevadm", "control", "--reload-rules"])
print(f"{G}✓{NC}")
removed += 1
except Exception as e:
print(f"{Y}skip ({e}){NC}")
# Cloned repos
if REPOS_DIR.exists():
step(f"Removing cloned repos ({REPOS_DIR})...")
try:
shutil.rmtree(REPOS_DIR, ignore_errors=True)
print(f"{G}✓{NC}")
removed += 1
except Exception as e:
print(f"{Y}skip ({e}){NC}")
# Status file
if STATUS_FILE.exists():
step("Removing setup status...")
try:
STATUS_FILE.unlink()
print(f"{G}✓{NC}")
removed += 1
except Exception as e:
print(f"{Y}skip ({e}){NC}")
# Symlinked binaries from /usr/local/bin (avbtool, etc.)
for link_name in ["avbtool"]:
link_path = Path("/usr/local/bin") / link_name
if link_path.is_symlink():
step(f"Removing symlink {link_path}...")
try:
link_path.unlink()
print(f"{G}✓{NC}")
removed += 1
except Exception as e:
print(f"{Y}skip ({e}){NC}")
# pip packages — only prompt before removing
print()
if removed:
ok(f"Removed {removed} installed artifacts")
else:
info("No WatchROM artifacts found — already clean")
print(f"\n {Y}Note: pip packages installed for WatchROM are left in place{NC}")
print(f" {DIM} to avoid breaking other tools. Remove manually if desired:{NC}")
pkgs = " ".join(PIP_PACKAGES.keys())
print(f" {DIM} pip3 uninstall {pkgs}{NC}\n")
def main():
print(BANNER)
# --uninstall
if "--uninstall" in sys.argv:
uninstall()
return
# --dry-run
if "--dry-run" in sys.argv:
show_plan()
return
# Check if re-run or first run
status = load_status()
first_run = not status.get("setup_complete", False)
if first_run:
print(f" {W}First-run setup detected. Installing all dependencies...{NC}\n")
else:
print(f" {DIM}Re-running setup (use --force to reinstall everything){NC}")
if "--force" not in sys.argv:
# Just show verify and exit
tools = verify_tools()
print_summary(tools, status)
return
# Run all installers
try:
status = install_apt_packages(status)
save_status(status)
status = install_pip_packages(status)
save_status(status)
status = install_binary_tools(status)
save_status(status)
status = clone_github_repos(status)
save_status(status)
status = setup_udev(status)
save_status(status)
status = install_watchrom_cli(status)
save_status(status)
tool_status = verify_tools()
status["setup_complete"] = True
status["setup_time"] = time.strftime("%Y-%m-%d %H:%M:%S")
save_status(status)
print_summary(tool_status, status)
except KeyboardInterrupt:
print(f"\n\n {Y}Setup interrupted. Run again to continue.{NC}\n")
sys.exit(1)
except Exception as e:
print(f"\n {R}Setup error: {e}{NC}")
import traceback; traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()