-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprep_disk.py
More file actions
executable file
·1500 lines (1169 loc) · 47.9 KB
/
Copy pathprep_disk.py
File metadata and controls
executable file
·1500 lines (1169 loc) · 47.9 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 python3
import importlib.util
import json
import math
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
# Label rendering defaults / fallbacks
DEFAULT_LABEL_SHORT_MM = 41
DEFAULT_LABEL_LONG_MM = 89
LABEL_DPI = 300
MM_PER_INCH = 25.4
PT_PER_INCH = 72.0
LABEL_MARGIN_X = 40
LABEL_MARGIN_Y = 40
LABEL_GAP = 25
TARGET_TEXT_WIDTH_MM = 70
FONT_CANDIDATES = [
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf",
"/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
]
def run(cmd, check=True, capture_output=True, text=True):
return subprocess.run(
cmd,
check=check,
capture_output=capture_output,
text=text
)
def require_root():
if os.geteuid() != 0:
print("This script must be run as root.")
print("Run it with: sudo ./prep_disk.py")
sys.exit(1)
def python_module_exists(module_name):
return importlib.util.find_spec(module_name) is not None
def check_prerequisites():
required_commands = {
"lsblk": "util-linux",
"findmnt": "util-linux",
"smartctl": "smartmontools",
"parted": "parted",
"partprobe": "parted",
"mkfs.exfat": "exfatprogs",
"wipefs": "util-linux",
"dd": "coreutils",
"udevadm": "udev",
"blockdev": "util-linux",
"umount": "util-linux",
"mount": "util-linux",
"cp": "coreutils",
"lp": "cups-client",
"lpstat": "cups-client",
"lpoptions": "cups-client",
}
required_python_modules = {
"PIL": "python3-pil",
}
missing_packages = set()
print("\nChecking required tools...\n")
for cmd, pkg in required_commands.items():
if shutil.which(cmd) is None:
print(f"Missing: {cmd} (package: {pkg})")
missing_packages.add(pkg)
for module_name, pkg in required_python_modules.items():
if not python_module_exists(module_name):
print(f"Missing Python module: {module_name} (package: {pkg})")
missing_packages.add(pkg)
if not missing_packages:
print("All required tools are installed.\n")
return
print("\nThe following packages need to be installed:")
for pkg in sorted(missing_packages):
print(f" {pkg}")
choice = input("\nInstall them now? [Y/n]: ").strip().lower()
if choice in ("", "y", "yes"):
print("\nInstalling required packages...\n")
update_result = subprocess.run(["apt", "update"])
if update_result.returncode != 0:
print("apt update failed. Please install the missing packages manually.")
sys.exit(1)
install_cmd = ["apt", "install", "-y"] + sorted(missing_packages)
install_result = subprocess.run(install_cmd)
if install_result.returncode != 0:
print("Package installation failed. Please install manually and run again.")
sys.exit(1)
print("\nDependencies installed successfully.\n")
else:
print("\nPlease install the required packages and run again.")
print(f"Example: sudo apt install {' '.join(sorted(missing_packages))}")
sys.exit(1)
def sanitize_filename(value):
value = (value or "").strip()
if not value:
value = "Unknown"
value = re.sub(r'[\\/*?:"<>|]', '-', value)
value = re.sub(r"\s+", " ", value).strip(" .")
return value if value else "Unknown"
def sanitize_folder_name(value):
value = (value or "").strip()
if not value:
value = "UnknownSerial"
value = re.sub(r'[\\/*?:"<>|]', '-', value)
value = re.sub(r"\s+", " ", value).strip(" .")
return value if value else "UnknownSerial"
def sanitize_exfat_label(value):
value = (value or "").strip()
if not value:
value = "NO_SERIAL"
value = re.sub(r"[^A-Za-z0-9 _-]", "", value)
value = re.sub(r"\s+", " ", value).strip()
if not value:
value = "NO_SERIAL"
return value[:15]
def sanitize_label_text(value, fallback):
value = (value or "").strip()
value = re.sub(r"[\r\n\t]+", " ", value)
value = re.sub(r"\s+", " ", value).strip()
return value if value else fallback
def human_size(num_bytes):
size = float(num_bytes)
units = ["B", "KB", "MB", "GB", "TB", "PB"]
for unit in units:
if size < 1024 or unit == units[-1]:
return f"{size:.2f} {unit}"
size /= 1024
def get_root_parent_disk():
try:
root_source = run(["findmnt", "-n", "-o", "SOURCE", "/"]).stdout.strip()
if not root_source.startswith("/dev/"):
return None
base = os.path.basename(root_source)
nvme_match = re.match(r"^(nvme\d+n\d+)p\d+$", base)
if nvme_match:
return f"/dev/{nvme_match.group(1)}"
mmc_match = re.match(r"^(mmcblk\d+)p\d+$", base)
if mmc_match:
return f"/dev/{mmc_match.group(1)}"
sd_match = re.match(r"^([a-zA-Z]+)\d+$", base)
if sd_match and not base.startswith(("nvme", "mmcblk", "loop")):
parent = re.sub(r"\d+$", "", base)
return f"/dev/{parent}"
return None
except Exception:
return None
def get_root_pkname():
try:
root_source = run(["findmnt", "-n", "-o", "SOURCE", "/"]).stdout.strip()
if not root_source.startswith("/dev/"):
return None
result = run(["lsblk", "-no", "PKNAME", root_source], check=False)
pkname = result.stdout.strip()
return pkname if pkname else None
except Exception:
return None
def get_disk_size_bytes(dev_name):
sys_size = Path(f"/sys/class/block/{dev_name}/size")
if sys_size.exists():
try:
sectors = int(sys_size.read_text().strip())
return sectors * 512
except Exception:
pass
try:
result = run(["blockdev", "--getsize64", f"/dev/{dev_name}"], check=False)
if result.returncode == 0 and result.stdout.strip().isdigit():
return int(result.stdout.strip())
except Exception:
pass
return 0
def get_disks():
result = run([
"lsblk",
"-J",
"-d",
"-b",
"-o",
"NAME,SIZE,MODEL,SERIAL,VENDOR,TYPE,TRAN,RM,RO,HOTPLUG"
])
data = json.loads(result.stdout)
disks = []
root_disk_by_path = get_root_parent_disk()
root_pkname = get_root_pkname()
for dev in data.get("blockdevices", []):
if dev.get("type") != "disk":
continue
path = f"/dev/{dev['name']}"
is_root_disk = (path == root_disk_by_path) or (dev["name"] == root_pkname)
size_raw = dev.get("size", 0)
try:
size_bytes = int(size_raw)
except Exception:
size_bytes = 0
if size_bytes <= 0:
size_bytes = get_disk_size_bytes(dev["name"])
disks.append({
"path": path,
"name": dev["name"],
"size_bytes": size_bytes,
"size_human": human_size(size_bytes) if size_bytes > 0 else "Unknown",
"model": (dev.get("model") or "").strip(),
"serial": (dev.get("serial") or "").strip(),
"vendor": (dev.get("vendor") or "").strip(),
"tran": (dev.get("tran") or "").strip(),
"rm": str(dev.get("rm", "")),
"ro": str(dev.get("ro", "")),
"hotplug": str(dev.get("hotplug", "")),
"is_root_disk": is_root_disk
})
return disks
def get_partition_path(disk_path):
base = os.path.basename(disk_path)
if re.search(r"^(nvme\d+n\d+|mmcblk\d+)$", base):
return disk_path + "p1"
return disk_path + "1"
#def collect_smart_report(disk_path):
# result = run(["smartctl", "-x", disk_path], check=False)
# output = result.stdout or ""
# if result.stderr:
# output += "\n" + result.stderr
# return output
def score_smart_output(text):
score = 0
if not text:
return score
patterns = [
r"SMART overall-health self-assessment test result",
r"ID#\s+ATTRIBUTE_NAME",
r"Power_On_Hours",
r"Reallocated_Sector_Ct",
r"Current_Pending_Sector",
r"Offline_Uncorrectable",
r"Power_Cycle_Count",
r"Temperature_Celsius",
r"Current Drive Temperature",
r"Serial Number:",
r"Model Family:",
r"Device Model:",
r"User Capacity:",
r"Vendor Specific SMART Attributes with Thresholds:",
]
for pattern in patterns:
if re.search(pattern, text, re.IGNORECASE | re.MULTILINE):
score += 10
# Prefer outputs that are longer, up to a point
score += min(len(text) // 200, 50)
# Penalize obvious failures a bit
failure_patterns = [
r"Unknown USB bridge",
r"Please specify device type",
r"SMART support is:\s+Unavailable",
r"Read Device Identity failed",
r"A mandatory SMART command failed",
]
for pattern in failure_patterns:
if re.search(pattern, text, re.IGNORECASE):
score -= 15
return score
def collect_smart_report(disk_path):
probe_cmds = [
["smartctl", "-x", disk_path],
["smartctl", "-x", "-d", "sat", disk_path],
["smartctl", "-x", "-d", "sat,12", disk_path],
["smartctl", "-x", "-d", "sat,16", disk_path],
["smartctl", "-x", "-d", "scsi", disk_path],
["smartctl", "-x", "-d", "usbjmicron", disk_path],
["smartctl", "-x", "-d", "usbprolific", disk_path],
["smartctl", "-x", "-d", "usbsunplus", disk_path],
]
best_output = ""
best_score = -9999
best_cmd = None
for cmd in probe_cmds:
result = run(cmd, check=False)
output = result.stdout or ""
if result.stderr:
output += "\n" + result.stderr
score = score_smart_output(output)
if score > best_score:
best_score = score
best_output = output
best_cmd = cmd
header = []
header.append("SMART COLLECTION METHOD")
header.append("=" * 72)
header.append(f"Command used: {' '.join(best_cmd) if best_cmd else 'Unknown'}")
header.append(f"Score: {best_score}")
header.append("")
return "\n".join(header) + best_output
def get_identity_for_filename(disk):
vendor = sanitize_filename(disk["vendor"] or "UnknownMake")
model = sanitize_filename(disk["model"] or "UnknownModel")
serial = sanitize_filename(disk["serial"] or "UnknownSerial")
return vendor, model, serial
def get_report_dir(script_dir, disk):
serial = sanitize_folder_name(disk.get("serial") or "UnknownSerial")
report_dir = Path(script_dir) / serial
report_dir.mkdir(parents=True, exist_ok=True)
return report_dir
def extract_first_match(patterns, text, flags=re.MULTILINE):
for pattern in patterns:
match = re.search(pattern, text, flags | re.IGNORECASE)
if match:
return match.group(1).strip()
return "Unknown"
def extract_temperature_celsius(smart_text):
patterns = [
r"Current Drive Temperature:\s+(\d+)\s*C",
r"Temperature:\s+(\d+)\s+Celsius",
r"Temperature Sensor \d+:\s+(\d+)\s+Celsius",
r"^\s*194\s+Temperature_Celsius\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*190\s+Airflow_Temperature_Cel\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*190\s+Temperature_Internal\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
]
value = extract_first_match(patterns, smart_text)
if value.isdigit():
return int(value)
return None
def extract_total_host_writes(smart_text):
matches = [
re.search(r"Data Units Written:\s*([\d,]+)", smart_text),
re.search(r"Host Writes:\s*([\d,]+)", smart_text),
re.search(r"Total Host Writes:\s*([\d,]+)\s*GB", smart_text),
]
for m in matches:
if m:
return m.group(1).replace(",", "")
return None
def parse_smart_summary(smart_text, disk):
summary = {
"Make": disk.get("vendor") or "Unknown",
"Model": disk.get("model") or "Unknown",
"Serial Number": disk.get("serial") or "Unknown",
"Capacity": disk.get("size_human") or "Unknown",
"Interface": disk.get("tran") or "Unknown",
"SMART Overall Health": "Unknown",
"Power-On Hours": "Unknown",
"Power Cycle Count": "Unknown",
"Reallocated Sectors": "Unknown",
"Current Pending Sectors": "Unknown",
"Offline Uncorrectable": "Unknown",
"Temperature": "Unknown",
"Total Host Writes": "Unknown",
}
health = extract_first_match([
r"SMART overall-health self-assessment test result:\s*(.+)",
r"SMART Health Status:\s*(.+)",
r"SMART overall-health self-assessment test result\s*:\s*(.+)",
r"SMART overall-health self-assessment test result =\s*(.+)",
], smart_text)
poh = extract_first_match([
r"^\s*9\s+Power_On_Hours\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*9\s+Power_On_Hours\s+\S+.*?(\d+)\s*$",
r"Power on hours:\s*(.+)",
r"Accumulated power on time, hours:\s*(.+)"
], smart_text)
pcc = extract_first_match([
r"^\s*12\s+Power_Cycle_Count\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*12\s+Power_Cycle_Count.*?(\d+)\s*$",
r"Power cycle count:\s*(.+)",
r"start[- ]stop count:\s*(.+)",
], smart_text)
realloc = extract_first_match([
r"^\s*5\s+Reallocated_Sector_Ct\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*5\s+Reallocated_Sector_Ct.*?(\d+)\s*$",
r"Reallocated sector count:\s*(.+)",
r"Elements in grown defect list:\s*(.+)",
], smart_text)
pending = extract_first_match([
r"^\s*197\s+Current_Pending_Sector\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*197\s+Current_Pending_Sector.*?(\d+)\s*$",
r"Current pending sector count:\s*(.+)",
], smart_text)
offline_unc = extract_first_match([
r"^\s*198\s+Offline_Uncorrectable\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\d+)\s*$",
r"^\s*198\s+Offline_Uncorrectable.*?(\d+)\s*$",
r"Offline uncorrectable sector count:\s*(.+)",
], smart_text)
temp_c = extract_temperature_celsius(smart_text)
host_writes = extract_total_host_writes(smart_text)
summary["SMART Overall Health"] = health
summary["Power-On Hours"] = poh
summary["Power Cycle Count"] = pcc
summary["Reallocated Sectors"] = realloc
summary["Current Pending Sectors"] = pending
summary["Offline Uncorrectable"] = offline_unc
summary["Temperature"] = f"{temp_c} C" if temp_c is not None else "Unknown"
summary["Total Host Writes"] = host_writes if host_writes else "Unknown"
return summary
def parse_ata_smart_attributes(smart_text):
attributes = []
lines = smart_text.splitlines()
table_started = False
for line in lines:
stripped = line.rstrip()
if re.search(r"ID#\s+ATTRIBUTE_NAME\s+FLAG\s+VALUE\s+WORST\s+THRESH\s+TYPE\s+UPDATED\s+WHEN_FAILED\s+RAW_VALUE", stripped):
table_started = True
continue
if table_started:
if not stripped.strip():
break
m = re.match(
r"^\s*(\d+)\s+([A-Za-z0-9_\-]+)\s+([0-9A-Fa-fx]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+?)\s*$",
stripped
)
if m:
attributes.append({
"id": m.group(1),
"name": m.group(2).replace("_", " "),
"current": m.group(4),
"worst": m.group(5),
"threshold": m.group(6),
"raw": m.group(10).strip(),
})
else:
# If we hit something clearly no longer table-ish, bail out.
if not re.match(r"^\s*\d+\s+", stripped):
break
return attributes
def format_summary_block(summary):
lines = []
lines.append("LISTING SUMMARY")
lines.append("=" * 72)
ordered_keys = [
"Make",
"Model",
"Serial Number",
"Capacity",
"Interface",
"SMART Overall Health",
"Temperature",
"Power-On Hours",
"Power Cycle Count",
"Total Host Writes",
"Reallocated Sectors",
"Current Pending Sectors",
"Offline Uncorrectable",
]
for key in ordered_keys:
lines.append(f"{key}: {summary.get(key, 'Unknown')}")
lines.append("")
lines.append("Suggested listing note:")
lines.append(
f"{summary['Model']} hard drive, {summary['Capacity']}, "
f"tested and formatted exFAT. "
f"SMART health: {summary['SMART Overall Health']}. "
f"Temperature: {summary['Temperature']}. "
f"Power-on hours: {summary['Power-On Hours']}. "
f"Reallocated sectors: {summary['Reallocated Sectors']}. "
f"Pending sectors: {summary['Current Pending Sectors']}."
)
return "\n".join(lines)
def write_report(script_dir, disk, report_text, summary_text):
vendor, model, serial = get_identity_for_filename(disk)
report_dir = get_report_dir(script_dir, disk)
filename = f"{vendor} - {model} - {serial}.txt"
path = report_dir / filename
with open(path, "w", encoding="utf-8") as f:
f.write("Drive Report\n")
f.write("=" * 72 + "\n")
f.write(f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Disk Path: {disk['path']}\n")
f.write(f"Vendor: {disk['vendor'] or 'Unknown'}\n")
f.write(f"Model: {disk['model'] or 'Unknown'}\n")
f.write(f"Serial: {disk['serial'] or 'Unknown'}\n")
f.write(f"Size: {disk['size_human']}\n")
f.write(f"Transport: {disk['tran'] or 'Unknown'}\n")
f.write("\nSMART / DRIVE DATA\n")
f.write("=" * 72 + "\n")
f.write(report_text.rstrip() + "\n\n")
f.write(summary_text.rstrip() + "\n")
return path
def draw_vertical_gradient(img, top_rgb, bottom_rgb):
from PIL import ImageDraw
draw = ImageDraw.Draw(img)
width, height = img.size
for y in range(height):
r = int(top_rgb[0] + (bottom_rgb[0] - top_rgb[0]) * (y / max(1, height - 1)))
g = int(top_rgb[1] + (bottom_rgb[1] - top_rgb[1]) * (y / max(1, height - 1)))
b = int(top_rgb[2] + (bottom_rgb[2] - top_rgb[2]) * (y / max(1, height - 1)))
draw.line((0, y, width, y), fill=(r, g, b))
def create_smart_graphic_png(script_dir, disk, summary, smart_text, tested_timestamp):
from PIL import Image, ImageDraw, ImageFont
vendor, model, serial = get_identity_for_filename(disk)
report_dir = get_report_dir(script_dir, disk)
filename = f"{vendor} - {model} - {serial}.png"
path = report_dir / filename
width = 1700
margin = 30
panel_gap = 18
left_col_w = 260
top_panel_h = 300
attrs = parse_ata_smart_attributes(smart_text)
font_path_bold = get_font_path()
font_path_regular = None
for p in FONT_CANDIDATES:
if Path(p).exists() and "Bold" not in Path(p).name:
font_path_regular = p
break
if font_path_regular is None:
font_path_regular = font_path_bold
title_font = ImageFont.truetype(font_path_bold, 40)
small_title_font = ImageFont.truetype(font_path_bold, 24)
big_box_font = ImageFont.truetype(font_path_bold, 38)
medium_font = ImageFont.truetype(font_path_regular, 28)
medium_bold_font = ImageFont.truetype(font_path_bold, 28)
small_font = ImageFont.truetype(font_path_regular, 24)
table_font = ImageFont.truetype(font_path_regular, 24)
table_bold_font = ImageFont.truetype(font_path_bold, 24)
table_row_h = 34
table_header_h = 42
table_h = table_header_h + (len(attrs) * table_row_h if attrs else 2 * table_row_h)
footer_h = 55
height = margin + top_panel_h + panel_gap + table_h + panel_gap + footer_h + margin
img = Image.new("RGB", (width, height), (236, 242, 250))
draw = ImageDraw.Draw(img)
draw_vertical_gradient(img, (239, 245, 252), (219, 231, 244))
def rounded_box(x1, y1, x2, y2, fill, outline, radius=22, width_px=2):
draw.rounded_rectangle((x1, y1, x2, y2), radius=radius, fill=fill, outline=outline, width=width_px)
def gradient_badge(x1, y1, x2, y2, top_rgb, bottom_rgb, outline=(112, 143, 205), radius=26):
badge_w = x2 - x1
badge_h = y2 - y1
badge = Image.new("RGB", (badge_w, badge_h), (255, 255, 255))
draw_vertical_gradient(badge, top_rgb, bottom_rgb)
mask = Image.new("L", (badge_w, badge_h), 0)
from PIL import ImageDraw as ID
md = ID.Draw(mask)
md.rounded_rectangle((0, 0, badge_w - 1, badge_h - 1), radius=radius, fill=255)
img.paste(badge, (x1, y1), mask)
draw.rounded_rectangle((x1, y1, x2, y2), radius=radius, outline=outline, width=2)
header_x1 = margin
header_y1 = margin
header_x2 = width - margin
header_y2 = margin + 95
rounded_box(header_x1, header_y1, header_x2, header_y2, (255, 255, 255), (170, 186, 210), 18, 2)
model_header = disk.get("model") or "Unknown Model"
size_header = disk.get("size_human") or "Unknown Size"
title_text = f"{model_header} | {size_header} | Tested: {tested_timestamp}"
draw.text((header_x1 + 25, header_y1 + 20), title_text, font=title_font, fill=(20, 30, 50))
left_x1 = margin
left_y1 = header_y2 + panel_gap
left_x2 = left_x1 + left_col_w
left_y2 = left_y1 + top_panel_h
rounded_box(left_x1, left_y1, left_x2, left_y2, (255, 255, 255), (170, 186, 210), 20, 2)
draw.text((left_x1 + 18, left_y1 + 16), "Health Status", font=small_title_font, fill=(40, 55, 80))
health_text = summary.get("SMART Overall Health", "Unknown")
health_clean = health_text.upper()
if "PASS" in health_clean or "GOOD" in health_clean or "OK" in health_clean:
health_fill_top = (202, 227, 255)
health_fill_bottom = (83, 173, 231)
health_outline = (94, 131, 210)
health_primary = "GOOD"
else:
health_fill_top = (255, 227, 193)
health_fill_bottom = (255, 171, 77)
health_outline = (196, 124, 55)
health_primary = health_text[:14] if health_text != "Unknown" else "UNKNOWN"
gradient_badge(left_x1 + 18, left_y1 + 56, left_x2 - 18, left_y1 + 150,
health_fill_top, health_fill_bottom, health_outline, 18)
health_primary_box = draw.textbbox((0, 0), health_primary, font=big_box_font)
hpw = health_primary_box[2] - health_primary_box[0]
draw.text((left_x1 + ((left_col_w - hpw) // 2), left_y1 + 76), health_primary,
font=big_box_font, fill=(10, 20, 40))
detail_text = health_text if health_text != health_primary else ""
if detail_text:
detail_box = draw.textbbox((0, 0), detail_text, font=small_font)
dtw = detail_box[2] - detail_box[0]
draw.text((left_x1 + ((left_col_w - dtw) // 2), left_y1 + 118),
detail_text, font=small_font, fill=(10, 20, 40))
draw.text((left_x1 + 18, left_y1 + 182), "Temperature", font=small_title_font, fill=(40, 55, 80))
temp_text = summary.get("Temperature", "Unknown")
gradient_badge(left_x1 + 18, left_y1 + 220, left_x2 - 18, left_y1 + 286,
(200, 216, 255), (95, 196, 239), (94, 131, 210), 30)
temp_box = draw.textbbox((0, 0), temp_text, font=big_box_font)
tw = temp_box[2] - temp_box[0]
draw.text((left_x1 + ((left_col_w - tw) // 2), left_y1 + 232),
temp_text, font=big_box_font, fill=(10, 20, 40))
right_x1 = left_x2 + panel_gap
right_y1 = left_y1
right_x2 = width - margin
right_y2 = left_y2
rounded_box(right_x1, right_y1, right_x2, right_y2, (255, 255, 255), (170, 186, 210), 20, 2)
info_fields = [
("Firmware", extract_first_match([r"Firmware Version:\s*(.+)", r"Firmware:\s*(.+)"], smart_text), None),
("Serial Number", summary["Serial Number"], None),
("Interface", extract_first_match([r"Transport protocol:\s*(.+)", r"Interface:\s*(.+)"], smart_text), None),
("Capacity", summary["Capacity"], None),
("Power On Count", summary["Power Cycle Count"], None),
("Power On Hours", summary["Power-On Hours"], None),
("Host Writes", summary["Total Host Writes"], "GB" if summary["Total Host Writes"] not in ("Unknown", "") else None),
("Transport", disk.get("tran") or "Unknown", None),
]
info_start_y = right_y1 + 22
label_x = right_x1 + 24
value_x = right_x1 + 260
row_h = 30
row_gap = 10
box_w = right_x2 - value_x - 20
for idx, (label, value, suffix) in enumerate(info_fields):
y = info_start_y + idx * (row_h + row_gap)
if y + row_h > right_y2 - 18:
break
draw.text((label_x, y + 2), label, font=medium_font, fill=(30, 45, 70))
draw.rounded_rectangle((value_x, y, value_x + box_w, y + row_h + 6),
radius=8, fill=(246, 248, 252), outline=(180, 190, 206), width=1)
value_display = value if value not in ("Unknown", "", None) else "----"
if suffix and value_display != "----":
value_display = f"{value_display} {suffix}"
draw.text((value_x + 10, y + 3), value_display, font=medium_font, fill=(20, 30, 50))
table_x1 = margin
table_y1 = left_y2 + panel_gap
table_x2 = width - margin
table_y2 = table_y1 + table_h
rounded_box(table_x1, table_y1, table_x2, table_y2, (255, 255, 255), (170, 186, 210), 20, 2)
col_x = {
"id": table_x1 + 24,
"name": table_x1 + 90,
"current": table_x1 + 760,
"worst": table_x1 + 930,
"threshold": table_x1 + 1090,
"raw": table_x1 + 1260,
}
header_y = table_y1 + 14
draw.text((col_x["id"], header_y), "ID", font=table_bold_font, fill=(25, 35, 60))
draw.text((col_x["name"], header_y), "Attribute Name", font=table_bold_font, fill=(25, 35, 60))
draw.text((col_x["current"], header_y), "Current", font=table_bold_font, fill=(25, 35, 60))
draw.text((col_x["worst"], header_y), "Worst", font=table_bold_font, fill=(25, 35, 60))
draw.text((col_x["threshold"], header_y), "Threshold", font=table_bold_font, fill=(25, 35, 60))
draw.text((col_x["raw"], header_y), "Raw Value", font=table_bold_font, fill=(25, 35, 60))
draw.line((table_x1 + 18, table_y1 + table_header_h, table_x2 - 18, table_y1 + table_header_h),
fill=(170, 186, 210), width=2)
if attrs:
for i, attr in enumerate(attrs):
row_y = table_y1 + table_header_h + (i * table_row_h)
fill = (248, 250, 253) if i % 2 == 0 else (238, 243, 249)
draw.rounded_rectangle((table_x1 + 14, row_y + 2, table_x2 - 14, row_y + table_row_h),
radius=6, fill=fill)
draw.ellipse((table_x1 + 22, row_y + 8, table_x1 + 38, row_y + 24),
fill=(96, 177, 235), outline=(88, 132, 199))
draw.text((col_x["id"], row_y + 4), attr["id"], font=table_font, fill=(20, 30, 50))
draw.text((col_x["name"], row_y + 4), attr["name"], font=table_font, fill=(20, 30, 50))
draw.text((col_x["current"], row_y + 4), attr["current"], font=table_font, fill=(20, 30, 50))
draw.text((col_x["worst"], row_y + 4), attr["worst"], font=table_font, fill=(20, 30, 50))
draw.text((col_x["threshold"], row_y + 4), attr["threshold"], font=table_font, fill=(20, 30, 50))
draw.text((col_x["raw"], row_y + 4), attr["raw"], font=table_font, fill=(20, 30, 50))
else:
msg = "SMART attribute table not available in a standard ATA format for this device."
draw.text((table_x1 + 24, table_y1 + table_header_h + 18), msg, font=medium_font, fill=(50, 60, 80))
draw.text((table_x1 + 24, table_y1 + table_header_h + 58),
"The text report still contains the full smartctl output.", font=small_font, fill=(70, 80, 100))
footer_y = table_y2 + panel_gap
rounded_box(margin, footer_y, width - margin, footer_y + footer_h, (255, 255, 255), (170, 186, 210), 16, 2)
footer_text = f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')} Source device: {disk['path']}"
draw.text((margin + 20, footer_y + 12), footer_text, font=small_font, fill=(45, 55, 75))
img.save(path, dpi=(300, 300))
return path
def unmount_disk_partitions(disk_path):
result = run(
["lsblk", "-J", "-o", "NAME,MOUNTPOINT", disk_path],
check=False
)
if result.returncode != 0 or not result.stdout.strip():
return
data = json.loads(result.stdout)
devices = data.get("blockdevices", [])
def walk(children):
mounts = []
for child in children or []:
name = child.get("name")
mountpoint = child.get("mountpoint")
if name and mountpoint:
mounts.append((name, mountpoint))
mounts.extend(walk(child.get("children", [])))
return mounts
for device in devices:
for name, mountpoint in walk(device.get("children", [])):
part_path = f"/dev/{name}"
print(f"Unmounting {part_path} from {mountpoint} ...")
run(["umount", part_path], check=False)
run(["sync"], check=False)
def quick_wipe(disk_path):
print(f"\nStarting quick wipe of {disk_path} ...")
unmount_disk_partitions(disk_path)
print("Removing known filesystem signatures...")
run(["wipefs", "-a", disk_path], check=False)
print("Blanking first 100 MiB...")
start_cmd = [
"dd",
"if=/dev/zero",
f"of={disk_path}",
"bs=1M",
"count=100",
"conv=fsync",
"status=progress"
]
start_proc = subprocess.run(start_cmd)
if start_proc.returncode != 0:
raise RuntimeError("Quick wipe failed while blanking the start of the disk.")
size_bytes = get_disk_size_bytes(os.path.basename(disk_path))
mib = 1024 * 1024
tail_size = 100 * mib
if size_bytes > tail_size:
seek_mib = (size_bytes - tail_size) // mib
print("Blanking last 100 MiB...")
end_cmd = [
"dd",
"if=/dev/zero",
f"of={disk_path}",
"bs=1M",
f"seek={seek_mib}",
"count=100",
"conv=fsync",
"status=progress"
]
end_proc = subprocess.run(end_cmd)
if end_proc.returncode != 0:
raise RuntimeError("Quick wipe failed while blanking the end of the disk.")
run(["sync"], check=False)
print("Quick wipe complete.")
def full_zero_wipe(disk_path):
print(f"\nStarting full zero wipe of {disk_path} ...")
print("This can take a while on larger drives.\n")
unmount_disk_partitions(disk_path)
cmd = [
"dd",
"if=/dev/zero",
f"of={disk_path}",
"bs=16M",
"conv=fsync",
"status=progress"
]
proc = subprocess.run(cmd)
if proc.returncode != 0:
raise RuntimeError("Full zero wipe failed.")
run(["sync"], check=False)
print("Full zero wipe complete.")
def wait_for_partition_node(part_path, timeout=15):
for _ in range(timeout):
if Path(part_path).exists():
return True
time.sleep(1)
return False
def format_exfat(part_path, label):
run(["udevadm", "settle"], check=False)
run(["umount", part_path], check=False)
print(f"Formatting {part_path} as exFAT ...")
if label:
print(f"Using volume label: {label}")
result = run(["mkfs.exfat", "-L", label, part_path], check=False)
if result.returncode == 0:
return
print("Formatting with label failed. Retrying without a label...")
result = run(["mkfs.exfat", part_path], check=False)
if result.returncode != 0:
raise RuntimeError(f"mkfs.exfat failed for {part_path}.")
def repartition_and_format_exfat(disk_path, disk):
print(f"\nCreating fresh MBR partition table on {disk_path} ...")
run(["parted", "-s", disk_path, "mklabel", "msdos"])
run(["parted", "-s", disk_path, "mkpart", "primary", "1MiB", "100%"])
run(["partprobe", disk_path], check=False)
run(["udevadm", "settle"], check=False)
part_path = get_partition_path(disk_path)
if not wait_for_partition_node(part_path, timeout=15):
raise RuntimeError(f"Partition device was not created: {part_path}")
label = sanitize_exfat_label(disk.get("serial") or "")
format_exfat(part_path, label)
return part_path, label
def mount_partition_temp(part_path):
mount_dir = Path("/tmp") / f"prep_drive_mount_{os.getpid()}"
mount_dir.mkdir(parents=True, exist_ok=True)
run(["udevadm", "settle"], check=False)
run(["mount", part_path, str(mount_dir)])
return mount_dir
def copy_files_to_drive(part_path, files_to_copy):
mount_dir = None
copied = []
try:
mount_dir = mount_partition_temp(part_path)
for src in files_to_copy:
destination = mount_dir / Path(src).name
shutil.copy2(src, destination)
copied.append(destination)
run(["sync"], check=False)
return copied
finally:
if mount_dir is not None:
run(["umount", str(mount_dir)], check=False)