-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfigure.py
More file actions
executable file
·450 lines (393 loc) · 16 KB
/
Copy pathconfigure.py
File metadata and controls
executable file
·450 lines (393 loc) · 16 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
#!/usr/bin/env python3
"""Interactive console configurator for Zenbook Duo keyboard scripts."""
from __future__ import annotations
import argparse
import configparser
import os
import subprocess
import sys
import traceback
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from zenbook_kb.install import (
cleanup_legacy_prefix,
detect_init_system,
install_all,
install_fan_control_support,
install_kb_brightness_tree,
install_sudoers_kb_brightness,
print_install_summary,
refresh_install_paths,
)
from zenbook_kb.dmi import has_platform_profile, has_screenpad_sysfs, is_ux5400, product_name
from zenbook_kb.paths import get_prefix
from zenbook_kb.users import default_duo_config, default_hotkeys_config, resolve_config_dir
EXAMPLE_CONFIG = Path(__file__).resolve().parent / "zenbook-duo.conf.example"
EXAMPLE_HOTKEYS = Path(__file__).resolve().parent / "zenbook-hotkeys.conf.example"
def prompt(label: str, default: str) -> str:
value = input(f"{label} [{default}]: ").strip()
return value or default
def yes_no(question: str, default_no: bool = True, *, assume_yes: bool = False) -> bool:
if assume_yes:
print(f"{question} → yes (--all-yes)", flush=True)
return True
suffix = "[y/N]" if default_no else "[Y/n]"
return input(f"{question} {suffix}: ").strip().lower().startswith("y")
def detect_keyboard() -> str:
try:
output = subprocess.check_output(["lsusb"], text=True)
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
if "1b2c" in output.lower():
return "usb"
return "bluetooth-or-absent"
def write_config(cfg: configparser.ConfigParser, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w") as fh:
cfg.write(fh)
def test_brightness(script_dir: Path, level: int) -> None:
cmd = [sys.executable, str(script_dir / "brightness.py"), str(level), "--show-mode"]
print(f"Running: {' '.join(cmd)}", flush=True)
subprocess.run(cmd, check=False)
def ensure_hotkeys_config() -> None:
default_hotkeys = default_hotkeys_config()
config_dir = resolve_config_dir()
if default_hotkeys.exists() or not EXAMPLE_HOTKEYS.exists():
return
config_dir.mkdir(parents=True, exist_ok=True)
default_hotkeys.write_text(EXAMPLE_HOTKEYS.read_text())
print(f"Created {default_hotkeys} (edit to bind unmapped Fn+ keys)", flush=True)
def resolve_fan_control_flag(args: argparse.Namespace) -> bool | None:
"""Return True/False when CLI forced; None = decide later (prompt / auto)."""
if args.include_fan_control and args.no_include_fan_control:
raise SystemExit("use only one of --include-fan-control / --no-include-fan-control")
if args.include_fan_control:
return True
if args.no_include_fan_control:
return False
return None
def resolve_kernel_flag(args: argparse.Namespace) -> bool | None:
"""Return True/False when CLI forced; None = decide later (prompt / skip)."""
if args.with_kernel and args.no_kernel:
raise SystemExit("use only one of --with-kernel / --no-kernel")
if args.with_kernel:
return True
if args.no_kernel:
return False
return None
def decide_kernel_install(
args: argparse.Namespace,
script_dir: Path,
*,
assume_yes: bool,
) -> tuple[bool, bool]:
"""Return (with_kernel, kernel_force).
``--all-yes`` does **not** auto-enable the kmod (must pass ``--with-kernel``).
"""
from zenbook_kb.dmi import is_ux8406
from zenbook_kb.kernel_preflight import SKIP_FEATURES_MSG, run_preflight
forced = resolve_kernel_flag(args)
force = bool(args.kernel_force) or os.environ.get(
"ZENBOOK_KERNEL_FORCE", ""
).strip().lower() in ("1", "yes", "true")
if forced is False:
print(f"Kernel module: skipped (--no-kernel).\n{SKIP_FEATURES_MSG}", flush=True)
return False, force
pf = run_preflight(repo_root=script_dir, force=force)
print("Kernel preflight:", flush=True)
for line in pf.summary_lines():
print(f" {line}", flush=True)
if forced is True:
if not pf.can_build and pf.risky and not force:
print(
"USE/--with-kernel requested but preflight is risky; "
"pass --kernel-force or ZENBOOK_KERNEL_FORCE=1 to continue.",
flush=True,
)
print(SKIP_FEATURES_MSG, flush=True)
return False, force
if not pf.eligible or not pf.has_source:
print(
"Cannot build oot hid-asus (ineligible or missing sources).",
flush=True,
)
print(SKIP_FEATURES_MSG, flush=True)
return False, force
return True, force
# Interactive / defaults path: only offer on UX8406 when eligible.
if not is_ux8406():
return False, force
if not pf.eligible or not pf.has_source:
print(
f"UX8406 detected but oot hid-asus cannot be built here.\n{SKIP_FEATURES_MSG}",
flush=True,
)
return False, force
if args.defaults and not assume_yes:
# --defaults alone: do not build kmod unless --with-kernel
print(
f"Kernel module: skipped (--defaults without --with-kernel).\n{SKIP_FEATURES_MSG}",
flush=True,
)
return False, force
if pf.risky and not force:
if assume_yes:
print(
"Risky kernel preflight; not auto-building under --all-yes. "
"Use --with-kernel --kernel-force.",
flush=True,
)
print(SKIP_FEATURES_MSG, flush=True)
return False, force
if not yes_no(
"Kernel looks unsupported or risky (see warnings). Build oot hid-asus anyway?",
default_no=True,
assume_yes=False,
):
print(SKIP_FEATURES_MSG, flush=True)
return False, force
force = True
if assume_yes:
# Still require explicit --with-kernel for kmod (handled above as forced).
print(
"Kernel module: skipped (--all-yes does not imply kmod; pass --with-kernel).",
flush=True,
)
print(SKIP_FEATURES_MSG, flush=True)
return False, force
if yes_no(
"Build and install oot hid-asus from kernel sources (replaces modular hid-asus)?",
default_no=True,
assume_yes=False,
):
return True, force
print(SKIP_FEATURES_MSG, flush=True)
return False, force
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Zenbook Duo keyboard configurator + installer")
parser.add_argument(
"--defaults",
action="store_true",
help="Do not prompt; use existing ~/.config values or project defaults",
)
parser.add_argument(
"--all-yes",
action="store_true",
help="Assume yes for all yes/no prompts (use with --defaults for semi-auto)",
)
parser.add_argument(
"--include-fan-control",
action="store_true",
help="Install adaptive platform-fan-control (config + OpenRC)",
)
parser.add_argument(
"--no-include-fan-control",
action="store_true",
help="Skip adaptive fan-control install (overrides auto / --all-yes)",
)
parser.add_argument(
"--with-kernel",
action="store_true",
help="Build+install oot hid-asus from local kernel sources (no prebuilt .ko)",
)
parser.add_argument(
"--no-kernel",
action="store_true",
help="Skip oot hid-asus build/install",
)
parser.add_argument(
"--kernel-force",
action="store_true",
help="Allow oot build on unsupported KV / MODVERSIONS (ack risk)",
)
parser.add_argument(
"--prefix",
default=None,
help="Install prefix (default: $ZENBOOK_PREFIX or /usr). Example: --prefix /usr",
)
parser.add_argument(
"--cleanup-usr-local",
action="store_true",
help="Remove leftover zenbook_scripts files under /usr/local after installing to --prefix",
)
parser.add_argument(
"--cleanup-dry-run",
action="store_true",
help="With --cleanup-usr-local, only list what would be removed",
)
args = parser.parse_args(argv)
# Interactive configure may ask for sudo password; daemons never do.
if sys.stdin.isatty() and "ZENBOOK_SUDO_ASK" not in os.environ:
os.environ["ZENBOOK_SUDO_ASK"] = "1"
prefix = refresh_install_paths(args.prefix)
_ = prefix # bound for side effect / logging via get_prefix()
script_dir = SCRIPT_DIR
default_config = default_duo_config()
cfg = configparser.ConfigParser()
if default_config.exists():
cfg.read(default_config)
elif EXAMPLE_CONFIG.exists():
cfg.read(EXAMPLE_CONFIG)
else:
cfg.read_dict(
{
"keyboard": {
"usb_vendor_id": "0b05",
"usb_product_id": "1b2c",
"bt_vendor_id": "0b05",
"bt_product_id": "1b2d",
"usb_windex": "4",
"default_brightness": "1",
},
"duo": {"default_backlight": "1", "default_scale": "1"},
}
)
kb = cfg["keyboard"]
duo = cfg.setdefault("duo", {})
init_system = detect_init_system()
dmi_name = product_name() or "unknown"
screenpad = has_screenpad_sysfs() or is_ux5400()
platform_profile = has_platform_profile()
fan_flag = resolve_fan_control_flag(args)
print("Zenbook Duo keyboard configurator", flush=True)
print(f"Detected DMI product: {dmi_name}", flush=True)
print(f"Detected connection: {detect_keyboard()}", flush=True)
print(f"Detected ScreenPad sysfs: {'yes' if has_screenpad_sysfs() else 'no'}", flush=True)
print(f"Detected platform_profile: {'yes' if platform_profile else 'no'}", flush=True)
print(
f"Detected init system: {init_system} "
f"({'systemctl found' if init_system == 'systemd' else 'OpenRC-like'})",
flush=True,
)
print(f"Install prefix: {get_prefix()}", flush=True)
print(flush=True)
if not args.defaults:
kb["usb_vendor_id"] = prompt("USB vendor ID (pogo pins)", kb.get("usb_vendor_id", "0b05"))
kb["usb_product_id"] = prompt("USB product ID", kb.get("usb_product_id", "1b2c"))
kb["bt_vendor_id"] = prompt("Bluetooth vendor ID", kb.get("bt_vendor_id", "0b05"))
kb["bt_product_id"] = prompt("Bluetooth product ID", kb.get("bt_product_id", "1b2d"))
kb["usb_windex"] = prompt("USB interface index (wIndex)", kb.get("usb_windex", "4"))
kb["default_brightness"] = prompt("Default brightness 0-3", kb.get("default_brightness", "1"))
# Legacy [duo] keys (old duo.sh); keep in sync for old conf files only.
duo["default_backlight"] = kb["default_brightness"]
duo.setdefault("default_scale", "1")
write_config(cfg, default_config)
ensure_hotkeys_config()
print(f"\nSaved {default_config}", flush=True)
if yes_no("Test brightness now?", default_no=True, assume_yes=args.all_yes):
test_brightness(script_dir, int(kb["default_brightness"]))
# --- collect install choices first (no side effects yet) ---
want_screenpad = False
want_screenpad_sync = False
if screenpad:
want_screenpad = yes_no(
"Install ScreenPad + platform-profile tools (UX5400 / asus_screenpad)?",
default_no=False,
assume_yes=args.all_yes,
)
if want_screenpad:
want_screenpad_sync = yes_no(
"Also install ScreenPad brightness-sync service?",
default_no=False,
assume_yes=args.all_yes,
)
with_fan: bool | None = fan_flag
if with_fan is None:
if not platform_profile:
with_fan = False
elif args.all_yes:
with_fan = True
else:
with_fan = yes_no(
"Install adaptive fan-control daemon (/etc/zenbook-scripts/fan-control.json)?",
default_no=False,
assume_yes=False,
)
want_full = yes_no(
f"Install kb-brightness + tools to {get_prefix()}?",
default_no=True,
assume_yes=args.all_yes,
)
with_hotkeys = False
if want_full:
with_hotkeys = yes_no(
f"Also install udev rules + {init_system} hotkey listener service?",
default_no=False,
assume_yes=args.all_yes,
)
elif not with_fan and not want_screenpad:
if yes_no("Install scripts only (no udev/service)?", default_no=True, assume_yes=args.all_yes):
want_full = True
with_hotkeys = False
with_kernel = False
kernel_force = bool(args.kernel_force)
if with_hotkeys or args.with_kernel:
with_kernel, kernel_force = decide_kernel_install(
args, script_dir, assume_yes=args.all_yes
)
elif args.no_kernel:
from zenbook_kb.kernel_preflight import SKIP_FEATURES_MSG
print(f"Kernel module: skipped (--no-kernel).\n{SKIP_FEATURES_MSG}", flush=True)
print("\n--- starting install (progress below) ---\n", flush=True)
try:
if want_full or want_screenpad or with_fan:
# One path: tree + optional pieces (avoids silent mid-prompt hangs).
if want_full or want_screenpad:
install_all(
script_dir,
with_hotkey_service=with_hotkeys if want_full else False,
with_screenpad=want_screenpad,
with_screenpad_sync=want_screenpad_sync,
with_fan_control=bool(with_fan),
fan_control_enable=bool(with_fan),
with_kernel=with_kernel,
kernel_force=kernel_force,
)
elif with_fan:
install_kb_brightness_tree(script_dir)
install_sudoers_kb_brightness()
install_fan_control_support(script_dir, enable_service=True, seed_config=True)
else:
print("Nothing selected to install.", flush=True)
if with_kernel and not with_hotkeys:
from zenbook_kb.install import build_and_install_hid_asus
build_and_install_hid_asus(script_dir, force=kernel_force)
except subprocess.TimeoutExpired as exc:
print(f"\nERROR: command timed out: {exc.cmd}", file=sys.stderr, flush=True)
print("Partial install possible — see summary.", file=sys.stderr, flush=True)
print_install_summary()
return 1
except Exception:
print("\nERROR during install:", file=sys.stderr, flush=True)
traceback.print_exc()
print_install_summary()
return 1
print_install_summary()
if args.cleanup_usr_local:
cleanup_legacy_prefix("/usr/local", dry_run=args.cleanup_dry_run)
elif str(get_prefix()) == "/usr" and not args.defaults:
if yes_no(
"Remove leftover zenbook_scripts files under /usr/local?",
default_no=False,
assume_yes=False,
):
cleanup_legacy_prefix("/usr/local", dry_run=args.cleanup_dry_run)
if with_hotkeys:
print("\nTry: kb-brightness-hotkeys --dry-run", flush=True)
if init_system == "openrc":
print("Service: rc-service zenbook-kb-hotkeys status", flush=True)
if with_kernel:
print("Kernel: oot hid-asus built from sources (see /usr/lib/modules/zenbook-hid-asus/)", flush=True)
if init_system == "openrc":
print("Service: rc-service zenbook-kb-hid-asus status", flush=True)
if with_fan:
print("Fan: platform-probe && platform-fan-control check", flush=True)
if init_system == "openrc":
print("Service: rc-service zenbook-platform-fan-control status", flush=True)
if want_screenpad:
print("Try: screenpad status && kb-platform-profile list", flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())