Compare commits

...

5 Commits

Author SHA1 Message Date
7e967de79b Split seven more linux_configuration scripts
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
10-recon.sh, install_exercism.sh, fix_arch_performance.sh,
format_sd_card.sh, setup_dot_resolver.sh, fix_unity.sh and
20-dump-stock.sh, all now under the cap.

Splitting a file twice is the risky move: the second cut on
20-dump-stock.sh dropped the first cut's source line, leaving
verify_dump called but never defined, and the repair then landed the
line inside the lib instead of the entry script. Both fixed - the entry
sources both libs and no lib sources another. Grep the source lines
after any double split.

fix_unity.sh's desktop_dir is read across the seam; renamed to
DESKTOP_DIR to match the file's own convention for globals.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:56:05 +02:00
58fdc6c9de Split five more linux_configuration single_use scripts
install_unreal_mcp.sh 395 -> 155, diagnose_arch_performance.sh 377 ->
123 (two cuts), setup_local_llm.sh 370 -> 163, repo_to_study.sh 365 ->
160, setup_dwm.sh 359 -> 147.

The SCRIPT_DIR fix from the last batch held on all five. Fixed a second
unguarded cd, this time before the study-material generator ran - the
same latent bug class as build_website, surfaced because a moved
function gets linted in isolation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:51:28 +02:00
1a75ed5bf5 Split three more linux_configuration feature and fix scripts
setup_syncyomi.sh 408 -> 138 (two cuts), setup_personal_website.sh
396 -> 192, fix_thorium.sh 377 -> 208.

All three already declared SCRIPT_DIR and the splitter added a second
one, which aborts at runtime with "readonly variable" while bash -n and
shellcheck stay clean. The stubbed run caught it; the splitter now
reuses an existing declaration.

Fixed SC2164 in build_website rather than suppressing it: a bare
cd "$WEBSITE_SRC" inside a subshell, with pnpm install and pnpm run
build after it. A failed cd would have built in the caller's directory.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:48:01 +02:00
9e62430b8d Split two more linux_configuration scripts; revert a third
control_from_mobile.sh 415 -> 180 and setup_periodic_system.sh 408 -> 228.

setup_periodic_system.sh has no main(): it defines functions then runs a
block of top-level calls, and the splitter moved that block into the lib,
changing when it ran. Redone by hand moving only definitions. It also
asks for sudo at source time, so the stubbed run is off-limits - verified
instead that the source line precedes the first call and all eleven
invoked functions are defined exactly once across the two files.

clean_audio.sh is reverted and stays over the cap. Two probe-result
globals are read from what would be two different libs, and renaming
them to satisfy SC2154 only moved the warning along. That is a refactor,
not a line-count split, and forcing it would have cost a suppression.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:44:18 +02:00
658988ef9b Split three near-miss linux_configuration scripts
turn_off_auto_idle_screen_shutdown.sh 289 -> 180, mtk_root/install.sh
262 -> 141, setup_gitea.sh 255 -> 198. A deliberately small batch to
check jscpd before scaling; it stayed well under 2%.

The stubbed run earned its place again: mtk_root/install.sh aborted with
"SCRIPT_DIR: readonly variable" because it already declared one, and
both bash -n and shellcheck were clean on that broken file.

Two shellcheck findings the split exposed are fixed at the source, not
suppressed: persist_with_systemd_logind now takes the flag as an
argument instead of reading the caller's global, and a dead python_bin
assignment is gone. Neither was introduced here - the pre-split file
already had three SC2034 warnings.

No script was executed; all three are installers or enforcement.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:38:43 +02:00
54 changed files with 3910 additions and 3343 deletions

View File

@ -80,6 +80,30 @@ grep -rn -E '^\s*(sudo )?(install|cp)\s.*(SCRIPT_DIR|REPO).*/usr/local/' \
linux_configuration --include='*.sh'
```
## Three traps found while splitting (2026-08-16)
- **A script with no `main()`.** `setup_periodic_system.sh` defines functions
and then runs a block of top-level calls. Moving that block into a lib
changes _when_ it runs. Move **only function definitions**; leave every
top-level invocation in the entry script, and check the `source` line comes
before the first call.
- **A script that needs root at source time.** The same file asks for sudo
while sourcing, so the stubbed run is not available. Fall back to: source
line before first call, plus every invoked function defined exactly once
across the two files (`grep -c '^fn() {'` in each).
- **An entry script that already declares `SCRIPT_DIR`** — often `readonly`.
Reuse it instead of adding a second declaration, or the script dies with
`readonly variable`. `bash -n` and `shellcheck` both pass on that.
### When to give up on a seam
`clean_audio.sh` was reverted. Two probe-result globals were read by functions
destined for different libs; renaming them to satisfy SC2154 just moved the
warning to a third. **A split that needs a suppression, or that would thread
globals through three files, is a refactor — not a line-count split.** Revert
it, leave the file over the cap, and say so. It is cheaper than a silent
behaviour change in a script you are not allowed to run.
- Prefer files that **nothing** references first — pure lint risk.
- Watch **jscpd** on the first multi-lib commit: repeated `set -euo pipefail` +
source-guard headers across several new libs is exactly what pushes

View File

@ -0,0 +1,19 @@
{
"title": "Split three near-miss linux_configuration scripts under the 250-line cap",
"objective": "Bring turn_off_auto_idle_screen_shutdown.sh (289), mtk_root/install.sh (262) and setup_gitea.sh (255) under the cap using the pattern established by the install_joplin.sh split, and prove the pattern holds on a small batch before scaling to the remaining 80 files.",
"acceptance_criteria": [
"All three entry scripts and all three new libs are at most 250 lines.",
"bash -n and shellcheck pass on every entry script and every new lib, with no new suppression and no shellcheck disable directive.",
"A stubbed run of each entry script -- copied into a mirrored temp tree, with the final main invocation replaced by a declare -F probe -- reports every moved function as defined. This is the check that replaces the pass count; static checks alone are known insufficient.",
"No enforcement script is executed. turn_off_auto_idle_screen_shutdown.sh in particular manipulates idle inhibition and logind and must not run.",
"The two live systemd units that point at repo paths still resolve to existing files.",
"jscpd stays under its 2% duplication threshold on the real git commit, which is the only place it runs.",
"No behaviour change: functions move verbatim, apart from the two shellcheck findings fixed below."
],
"out_of_scope": [
"Executing any installer or enforcement step.",
"The digital_wellbeing scripts, which are live enforcement and are deferred to the end with phone_focus_mode.",
"Changing what any script does when run."
],
"verifier": "The scratchpad verify_split.sh per script (bash -n + shellcheck -x + stubbed run), plus systemctl cat on the two repo-path units, plus pre-commit run --files, plus the real git commit for jscpd."
}

View File

@ -0,0 +1,18 @@
{
"title": "Split two more linux_configuration scripts, reverting a third",
"objective": "Bring control_from_mobile.sh (415) and setup_periodic_system.sh (408) under the 250-line cap, and establish when a seam should be abandoned rather than forced.",
"acceptance_criteria": [
"Both entry scripts and both new libs are at most 250 lines.",
"bash -n and shellcheck pass on every touched file, with no new suppression and no shellcheck disable directive.",
"setup_periodic_system.sh keeps its top-level invocation block in the entry script: it has no main(), so moving that block into a lib would change when it runs. Only function definitions move.",
"For any script that cannot be stub-run (setup_periodic_system.sh asks for root at source time), verification is: the source line precedes the first top-level call, and every invoked function is defined exactly once across the entry script and its lib.",
"No script is executed. Both install systemd units and one requires root.",
"clean_audio.sh is fully reverted, leaving no partial split and no new lib directory behind, and remains over the cap with the reason recorded."
],
"out_of_scope": [
"Executing any installer or enforcement step.",
"Untangling clean_audio.sh's cross-file globals, which is a refactor rather than a line-count split.",
"Changing what any script does when run."
],
"verifier": "scratchpad/verify_split.sh for control_from_mobile.sh; for setup_periodic_system.sh, bash -n + shellcheck -x plus grep proving source-before-call and one definition per invoked function; plus pre-commit run --files and the real git commit for jscpd."
}

View File

@ -0,0 +1,18 @@
{
"title": "Split three more linux_configuration feature and fix scripts",
"objective": "Bring setup_syncyomi.sh (408), setup_personal_website.sh (396) and fix_thorium.sh (377) under the 250-line cap, and teach the splitter to reuse an existing SCRIPT_DIR rather than redeclaring it.",
"acceptance_criteria": [
"All three entry scripts and all four new libs are at most 250 lines.",
"bash -n and shellcheck pass on every touched file, with no new suppression and no shellcheck disable directive.",
"Each entry script declares SCRIPT_DIR exactly once. All three already had one, and a second declaration aborts the script at runtime with 'readonly variable' while passing bash -n and shellcheck.",
"The stubbed run reports every moved function as defined, for all three scripts.",
"No script is executed. All three write Docker compose stacks, Caddy config or browser profile data.",
"The unchecked cd exposed in build_website is fixed rather than suppressed."
],
"out_of_scope": [
"Executing any setup or fix step.",
"clean_audio.sh and setup_passwordless_system.sh, both deferred for reasons already recorded.",
"Changing what any script does when run, beyond the cd guard."
],
"verifier": "scratchpad/verify_split.sh per script (bash -n + shellcheck -x + stubbed run), plus check_file_length.sh showing none of the six files, plus pre-commit run --files and the real git commit for jscpd."
}

View File

@ -0,0 +1,18 @@
{
"title": "Split five more linux_configuration single_use scripts",
"objective": "Bring install_unreal_mcp.sh (395), diagnose_arch_performance.sh (377), setup_local_llm.sh (370), repo_to_study.sh (365) and setup_dwm.sh (359) under the 250-line cap.",
"acceptance_criteria": [
"All five entry scripts and all six new libs are at most 250 lines.",
"bash -n and shellcheck pass on every touched file, with no new suppression and no shellcheck disable directive.",
"The stubbed run reports every moved function as defined, for all five scripts.",
"Each entry script still declares SCRIPT_DIR exactly once.",
"No script is executed. These install packages, write systemd and Ollama config, and build dwm from source.",
"The unchecked cd exposed in the repo_to_study steps is fixed rather than suppressed."
],
"out_of_scope": [
"Executing any install or diagnostic step.",
"fix_arch_performance.sh, a different file that is over the cap but was not touched here.",
"Changing what any script does when run, beyond the cd guard."
],
"verifier": "scratchpad/verify_split.sh per script (bash -n + shellcheck -x + stubbed run), plus check_file_length.sh showing none of the eleven files, plus pre-commit run --files and the real git commit for jscpd."
}

View File

@ -0,0 +1,18 @@
{
"title": "Split seven more linux_configuration scripts across mtk_root, utils, fixes and features",
"objective": "Bring 10-recon.sh (349), install_exercism.sh (330), fix_arch_performance.sh (326), format_sd_card.sh (323), setup_dot_resolver.sh (309), fix_unity.sh (302) and 20-dump-stock.sh (295) under the 250-line cap.",
"acceptance_criteria": [
"All seven entry scripts and all eight new libs are at most 250 lines.",
"bash -n and shellcheck pass on every touched file, with no new suppression and no shellcheck disable directive.",
"The stubbed run reports every moved function as defined, for all seven scripts.",
"When a script is split twice, the second split must not remove the first split's source line: every lib a script's functions live in is sourced by the entry script, and no lib sources another.",
"No script is executed. These read partitions over USB, format SD cards, install certificates and register MIME handlers.",
"The desktop_dir global read across the fix_unity split is resolved by matching the file's naming convention for globals, not by a suppression."
],
"out_of_scope": [
"Executing any recon, dump, format or install step. The mtk_root scripts in particular talk to a phone over USB.",
"The remaining no-main scripts (setup_passwordless_system.sh, nvidia_troubleshoot.sh, main.sh and the test harnesses), which need the by-hand treatment.",
"Changing what any script does when run."
],
"verifier": "scratchpad/verify_split.sh per script (bash -n + shellcheck -x + stubbed run), plus check_file_length.sh showing none of the fifteen files, plus pre-commit run --files and the real git commit for jscpd."
}

View File

@ -0,0 +1,51 @@
{
"intent": "Split three near-miss linux_configuration scripts under the cap, and confirm the shell-split pattern holds on a small batch before scaling it.",
"scope": [
"linux_configuration/scripts/single_use/utils/turn_off_auto_idle_screen_shutdown.sh (289 -> 180) + lib/idle_inhibit.sh",
"linux_configuration/scripts/mtk_root/install.sh (262 -> 141) + lib/mtk_udev.sh",
"linux_configuration/scripts/single_use/features/setup_gitea.sh (255 -> 198) + lib/gitea_network.sh",
"Non-goal: no script executed, no behaviour change"
],
"changes": [
"Moved the idle-inhibit process and controller watchers, the mtkclient udev/venv setup, and the Gitea firewall/UPnP/router block into sourced libs, each following the pattern from the install_joplin.sh commit: shebang, chmod +x, no set -euo pipefail, and SCRIPT_DIR via ${BASH_SOURCE[0]}.",
"mtk_root/install.sh already declared SCRIPT_DIR readonly, so the split reuses it rather than redeclaring; its existing $0 was upgraded to ${BASH_SOURCE[0]} at the same time.",
"Fixed two shellcheck findings the split exposed. persist_with_systemd_logind now takes the persist flag as an argument instead of reading the caller's global, so the lib is checkable standalone. python_bin in the mtkclient setup was assigned and never read - dead code, deleted rather than carried into the new file.",
"Neither finding was introduced by the split: shellcheck already reported three SC2034 warnings on the pre-split mtk_root/install.sh."
],
"verification": [
{
"command": "scratchpad/verify_split.sh <script> <moved functions> -- bash -n, shellcheck -x, then a stubbed run",
"result": "fail then pass",
"evidence": "All four scripts (including install_joplin.sh from the previous commit) now report 'libs sourced, functions defined'. The stubbed run found a real bug static checks missed: mtk_root/install.sh aborted with 'SCRIPT_DIR: readonly variable' because the splitter inserted a second declaration. bash -n and shellcheck were both clean on that broken file."
},
{
"command": "shellcheck on each new lib",
"result": "fail then pass",
"evidence": "SC2154 on persist_systemd and SC2034 on python_bin, both fixed at the source rather than suppressed. Clean afterwards."
},
{
"command": "systemctl cat dns-blocklist-refresh media-organizer, then test -f the ExecStart path",
"result": "pass",
"evidence": "Both resolve to existing files. Neither script was touched in this batch, but the check is cheap and these are the only two units pointing into the repo."
},
{
"command": "pre-commit run --files <changed>, then the real git commit for jscpd",
"result": "pass",
"evidence": "Clean. jscpd stayed under 2% with three new libs added at once, which is what the small first batch was sizing up - the libs carry no set -euo pipefail or source-guard boilerplate, which is what would have driven duplication."
},
{
"command": "wc -l",
"result": "pass",
"evidence": "Entry scripts 180, 141, 198; libs all under the cap."
}
],
"risks": [
"None of these scripts was run. turn_off_auto_idle_screen_shutdown.sh drives idle inhibition and logind, mtk_root/install.sh installs udev rules and a venv, and setup_gitea.sh opens a firewall port - all excluded by decision 6. The stubbed run proves the libs are reachable and the functions defined; it does not prove the scripts still do their job.",
"persist_with_systemd_logind's signature changed. Its only caller was updated in the same commit, and grep confirms there is no other.",
"The verifier mirrors the repo tree into a temp dir so repo-relative sources like ../../lib/common.sh resolve. A script sourcing something outside linux_configuration/scripts would not be covered by that mirror."
],
"rollback": [
"git revert the commit; the three scripts return to 289, 262 and 255 lines and the three libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored scripts."
]
}

View File

@ -0,0 +1,44 @@
{
"intent": "Split two more linux_configuration scripts under the cap, and record why a third was reverted rather than forced.",
"scope": [
"linux_configuration/scripts/single_use/features/control_from_mobile.sh (415 -> 180) + lib/mobile_service.sh",
"linux_configuration/scripts/periodic_background/setup_periodic_system.sh (408 -> 228) + lib/periodic_browser.sh",
"Reverted: scripts/single_use/misc/testsAndMisc-bash/clean_audio.sh",
"Non-goal: no script executed, no behaviour change"
],
"changes": [
"control_from_mobile.sh: the credential, env, runner-script and systemd-unit generation moved to lib/mobile_service.sh. Straightforward - it has a main() and no cross-file globals.",
"setup_periodic_system.sh has NO main(): it defines functions and then runs a block of top-level calls. The splitter's default behaviour moved that executing block into the lib, which would have changed when it ran. Caught by the stubbed run and redone by hand, moving only function definitions and leaving the invocation block in the entry script.",
"clean_audio.sh was reverted. Its two probe-result globals (use_arnndn, afftdn_supports_md) are read by functions in what would be two separate libs, and renaming them to uppercase to satisfy SC2154 only pushed the warning to a third variable. Untangling that is a real refactor, not a line-count split, and doing it here would have meant either a suppression or a behaviour risk."
],
"verification": [
{
"command": "scratchpad/verify_split.sh control_from_mobile.sh <moved functions>",
"result": "pass",
"evidence": "'libs sourced, functions defined' after bash -n and shellcheck -x."
},
{
"command": "static verification of setup_periodic_system.sh",
"result": "pass",
"evidence": "The stubbed run could NOT be used: the script requests sudo at source time, so running it is excluded by decision 6. Verified instead that the source line is at 176 and the first top-level call at 178, and that all eleven invoked functions are defined exactly once across the two files (six in the entry, five in the lib). bash -n and shellcheck -x clean on both."
},
{
"command": "git checkout + rm -rf lib, then shellcheck the restored clean_audio.sh",
"result": "pass",
"evidence": "Restored to 419 lines and clean, leaving no partial split behind."
},
{
"command": "pre-commit run --files <changed>",
"result": "pass",
"evidence": "Clean, including jscpd on the real commit with two more libs added."
}
],
"risks": [
"setup_periodic_system.sh requests root and installs systemd units; it was not run. The static check proves the lib is sourced before any call and that no function is missing or doubly defined, which is the strongest available evidence short of executing it.",
"clean_audio.sh remains over the cap at 419 lines and is now a known-harder case: its globals must be threaded explicitly, or the whole probe/filter section kept in one lib, before it can be split without a suppression."
],
"rollback": [
"git revert the commit; both scripts return to their previous sizes and the two libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored scripts."
]
}

View File

@ -0,0 +1,44 @@
{
"intent": "Split three more linux_configuration scripts under the cap, fixing a latent unchecked cd the split exposed.",
"scope": [
"linux_configuration/scripts/single_use/features/setup_syncyomi.sh (408 -> 138) + lib/syncyomi_stack.sh, lib/syncyomi_expose.sh",
"linux_configuration/scripts/single_use/features/setup_personal_website.sh (396 -> 192) + lib/website_build.sh",
"linux_configuration/scripts/single_use/fixes/fix_thorium.sh (377 -> 208) + lib/thorium_repairs.sh",
"Non-goal: no script executed"
],
"changes": [
"setup_syncyomi.sh needed two cuts: the compose/startup half went to syncyomi_stack.sh, which was still 279 lines, so the Caddy vhost, DuckDNS record and firewall rules went on to syncyomi_expose.sh.",
"All three entry scripts already declared SCRIPT_DIR, and the splitter had added a second declaration to each. That aborts the script with 'readonly variable' at runtime while passing bash -n and shellcheck; the stubbed run caught it on setup_personal_website.sh. Removed from all three, and the splitter now reuses an existing declaration.",
"Fixed SC2164 in build_website: a bare cd \"$WEBSITE_SRC\" inside a subshell, followed by pnpm install and pnpm run build. A failed cd would have run the build in whatever directory the caller happened to be in. Now guarded with || die."
],
"verification": [
{
"command": "scratchpad/verify_split.sh per script",
"result": "fail then pass",
"evidence": "setup_personal_website.sh first aborted with 'SCRIPT_DIR: readonly variable'. After the fix, all three report 'libs sourced, functions defined'."
},
{
"command": "shellcheck on each new lib",
"result": "fail then pass",
"evidence": "SC2164 on the unguarded cd in website_build.sh, fixed at the source. Clean afterwards, with no disable directive anywhere."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep <these files>",
"result": "pass",
"evidence": "No output - all three entry scripts and all four libs are under the cap."
},
{
"command": "pre-commit run --files <changed>, then the real git commit",
"result": "pass",
"evidence": "Clean, jscpd included, now with nine new libs across the linux_configuration commits."
}
],
"risks": [
"None of the three was run: they write Docker compose stacks, Caddy vhosts and browser profile data. The stubbed run proves the libs are reachable and the functions defined, not that the scripts still work end to end.",
"The cd guard is a behaviour change in the failure path only: previously the build would have run in the wrong directory, now it dies. That is the intended correction, but it is a change."
],
"rollback": [
"git revert the commit; the three scripts return to 408, 396 and 377 lines and the four libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored scripts."
]
}

View File

@ -0,0 +1,46 @@
{
"intent": "Split five more linux_configuration single_use scripts under the cap, fixing a second latent unchecked cd.",
"scope": [
"install_unreal_mcp.sh (395 -> 155) + lib/unreal_mcp_repo.sh",
"diagnose_arch_performance.sh (377 -> 123) + lib/arch_perf_probes.sh, lib/arch_perf_report.sh",
"setup_local_llm.sh (370 -> 163) + lib/local_llm_model.sh",
"repo_to_study.sh (365 -> 160) + lib/repo_study_steps.sh",
"setup_dwm.sh (359 -> 147) + lib/dwm_config.sh",
"Non-goal: no script executed"
],
"changes": [
"One cut each, except diagnose_arch_performance.sh: its first lib came out at 263 lines, so the GPU and journal probes, the safe-fix pass and the report summary moved on to a second lib.",
"All five already declared SCRIPT_DIR exactly once and the splitter correctly reused it, confirming the fix made in the previous batch.",
"Fixed SC2164 in the repo_to_study steps: a bare cd \"$analysis_dir\" immediately before invoking the study-material generator. A failed cd would have run the generator against the caller's directory. Now guarded with an error message and return 1 - the second instance of this same latent bug found by splitting."
],
"verification": [
{
"command": "scratchpad/verify_split.sh per script",
"result": "pass",
"evidence": "All five report 'libs sourced, functions defined' after bash -n and shellcheck -x. No SCRIPT_DIR collision this time."
},
{
"command": "shellcheck on each new lib",
"result": "fail then pass",
"evidence": "SC2164 on the unguarded cd in repo_study_steps.sh, fixed at the source. Clean afterwards."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep <these files>",
"result": "pass",
"evidence": "None of the eleven files listed. The only remaining hit in that grep is fix_arch_performance.sh, a different script that was already over the cap and is untouched here."
},
{
"command": "pre-commit run --files <changed>, then the real git commit",
"result": "pass",
"evidence": "Clean, jscpd included, now with fifteen new libs across the linux_configuration commits."
}
],
"risks": [
"None of the five was run: they install AUR packages, write Ollama modelfiles and systemd config, and compile dwm. The stubbed run proves the libs are reachable and the functions defined, not that the scripts still work end to end.",
"Two unchecked cd calls have now turned up in five splits. Others likely remain in unsplit files; splitting surfaces them because a moved function is linted in isolation."
],
"rollback": [
"git revert the commit; the five scripts return to their previous sizes and the six libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored scripts."
]
}

View File

@ -0,0 +1,48 @@
{
"intent": "Split seven more linux_configuration scripts under the cap, and fix a source line that a second split silently dropped.",
"scope": [
"mtk_root/10-recon.sh (349 -> 246) + lib/recon_report.sh",
"single_use/utils/install_exercism.sh (330 -> 174) + lib/exercism_config.sh",
"single_use/fixes/fix_arch_performance.sh (326 -> 215) + lib/arch_perf_fixes.sh",
"single_use/utils/format_sd_card.sh (323 -> 131) + lib/sd_card_ops.sh",
"single_use/features/setup_dot_resolver.sh (309 -> 162) + lib/dot_resolver_install.sh",
"single_use/misc/testsAndMisc-bash/fix_unity.sh (302 -> 236) + lib/unity_handler.sh",
"mtk_root/20-dump-stock.sh (295 -> 240) + lib/dump_verify.sh, lib/dump_partitions.sh",
"Non-goal: no script executed"
],
"changes": [
"One cut each, except 20-dump-stock.sh, which needed two.",
"The second cut on 20-dump-stock.sh dropped the first cut's source line for dump_verify.sh, so verify_dump was called but never defined, and then a repair added the line inside the wrong file. Both fixed: the entry script now sources both libs and neither lib sources the other.",
"fix_unity.sh's desktop_dir global is read by the moved functions. Renamed to DESKTOP_DIR, matching the convention the surrounding files already use for module-level globals - the same resolution as the earlier clean_audio.sh attempt, which works here because only one variable and two call sites are involved."
],
"verification": [
{
"command": "scratchpad/verify_split.sh per script",
"result": "fail then pass",
"evidence": "All seven now report 'libs sourced, functions defined'. Two failures on the way: SC1091 pointing at the misplaced dump_verify source line, and SC2154 on desktop_dir. Both were real - the first meant verify_dump was unreachable at runtime."
},
{
"command": "shellcheck -x on each entry script, shellcheck on each lib",
"result": "pass",
"evidence": "Clean. Note the verifier runs libs without -x, which is what surfaced the SC1091: a lib should never source a sibling, and the missing-file error is how that shows up."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep <these files>",
"result": "pass",
"evidence": "No output - all seven entry scripts and all eight libs are under the cap."
},
{
"command": "pre-commit run --files <changed>, then the real git commit",
"result": "pass",
"evidence": "Clean, jscpd included, now with twenty-three new libs across the linux_configuration commits."
}
],
"risks": [
"None of the seven was run. The mtk_root pair talk to a phone over USB and format_sd_card.sh writes partition tables; executing them to verify would be exactly what decision 6 forbids.",
"Splitting a file twice is the risky operation in this batch: the tool inserts its source line relative to the current file, so the second pass can land it in the wrong place or displace the first. Any double split needs its source lines grepped afterwards, which is how this one was caught."
],
"rollback": [
"git revert the commit; the seven scripts return to their previous sizes and the eight libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored scripts."
]
}

View File

@ -156,111 +156,8 @@ write_facts_file() {
printf '%s' "$out_path"
}
# ---------------------------------------------------------------------------
# Reporting
# ---------------------------------------------------------------------------
report_partitions() {
local carrier=""
carrier="$(mtk_ramdisk_carrier)"
mtk_heading "Partitions"
printf ' A/B scheme : %s\n' "$MTK_AB_SCHEME"
if [[ ${MTK_SLOT_ASSUMED:-0} -eq 1 ]]; then
printf ' slot suffix : %s (ASSUMED - ro.boot.slot_suffix was empty)\n' "${MTK_SLOT_SUFFIX:-none}"
else
printf ' slot suffix : %s\n' "${MTK_SLOT_SUFFIX:-none}"
fi
printf ' ramdisk lives in: %s -> partition %s\n' "${carrier:-UNKNOWN}" "${MTK_RAMDISK_PART:-NONE FOUND}"
printf ' vbmeta : %s\n' "${MTK_VBMETA_PART:-NONE FOUND}"
# boot vs init_boot is the single most consequential fact here: patching the
# wrong one produces a device that does not boot.
if [[ $carrier == "init_boot" ]]; then
printf ' => Magisk must patch INIT_BOOT on this device.\n'
elif [[ $carrier == "boot" ]]; then
printf ' => Magisk must patch BOOT on this device (no init_boot present).\n'
else
printf ' => Could not identify a ramdisk carrier. Do not flash anything.\n'
fi
mtk_check_layout_expectation || true
}
report_lock_state() {
mtk_heading "Lock state"
printf ' ro.boot.flash.locked : %s\n' "${UNLOCK_FLASH_LOCKED:-<unset>}"
printf ' ro.boot.verifiedbootstate : %s\n' "${UNLOCK_VBSTATE:-<unset>}"
printf ' ro.boot.vbmeta.device_state : %s\n' "${UNLOCK_DEVICE_STATE:-<unset>}"
printf ' sys.oem_unlock_allowed : %s\n' "${UNLOCK_SYS_ALLOWED:-<unset>}"
printf ' ro.oem_unlock_supported : %s\n' "${UNLOCK_OEM_SUPPORTED:-<unset>}"
printf ' settings oem_unlock_allowed : %s\n' "${UNLOCK_SETTING:-<unset>}"
printf '\n'
printf ' OEM-unlock toggle : %s\n' "$UNLOCK_TOGGLE"
printf ' Carrier lock : %s\n' "$(carrier_lock_verdict)"
printf '\n'
printf ' Carrier lock cannot be determined from any property. An unset\n'
printf ' sys.oem_unlock_allowed means the toggle is off, which is NOT the same\n'
printf ' as carrier-locked. Settle it out of band: check the IMEI with the\n'
printf ' carrier, or in the Google Store order record.\n'
}
report_manual_checks() {
mtk_heading "Check these on the phone screen yourself"
printf ' Settings > System > Developer options > "OEM unlocking":\n'
printf ' - toggleable => bootloader unlock is permitted by the firmware\n'
printf ' - greyed out => blocked (carrier policy, no network, or unsupported)\n'
printf ' A property can say the toggle is off; only the UI shows whether it\n'
printf ' CAN be turned on. That distinction decides the path.\n'
}
report_decision() {
mtk_heading "Decision summary"
# The companion document that defines paths A-D was not provided to the
# session that wrote this script, so the mapping below is inferred. Say so
# every run rather than let a plausible-looking verdict pass as authoritative.
printf ' \033[0;33mPATH SEMANTICS ARE ASSUMED\033[0m - the companion doc defining A/B/C/D was\n'
printf ' not available when this was written. Reconcile before acting.\n\n'
case "$MTK_DEVICE_CLASS" in
ULEFONE)
if [[ $UNLOCK_TOGGLE == "ON" ]]; then
printf ' => PATH A (Ulefone, OEM unlocking available)\n'
printf ' Next: ./20-dump-stock.sh --serial %s\n' "$MTK_SERIAL"
printf ' Then patch %s with Magisk and flash MANUALLY.\n' "${MTK_RAMDISK_PART:-<unknown>}"
else
printf ' => PATH A or B (Ulefone; toggle reads %s)\n' "$UNLOCK_TOGGLE"
printf ' Confirm the toggle on-screen before choosing.\n'
printf ' If greyed out => PATH B: fastboot unlock is blocked, leaving the\n'
printf ' mtkclient/BROM route, which is the untested one. Dump first:\n'
printf ' ./20-dump-stock.sh --serial %s\n' "$MTK_SERIAL"
fi
;;
PIXEL)
printf ' => PATH C or D (Pixel) - INDETERMINATE\n'
printf ' The toggle reads %s and carrier lock is UNDETERMINED, so C and D\n' "$UNLOCK_TOGGLE"
printf ' cannot be told apart from properties alone.\n\n'
printf ' \033[0;31mThis toolkit will not act on a Pixel.\033[0m It is the daily driver;\n'
printf ' recon only. No dump, unlock, or flash step here targets it.\n'
;;
*)
printf ' => NO PATH. Device did not classify.\n'
printf ' %s\n' "$MTK_CLASS_REASON"
printf ' Refusing to guess. Run --explain-classification, and if this is\n'
printf ' genuinely the Ulefone, widen the patterns at the top of\n'
printf ' lib/mtk_common.sh.\n'
;;
esac
mtk_heading "Still unknown"
printf ' - Whether the OEM unlocking toggle can be enabled (needs the screen)\n'
printf ' - Carrier lock status (needs an out-of-band IMEI check)\n'
if [[ $MTK_DEVICE_CLASS == "ULEFONE" ]]; then
printf ' - Whether this unit BROM is open or SLA/DAA-locked (needs mtkclient)\n'
printf ' - Whether fastboot flashing unlock is enabled in this firmware build\n'
fi
}
# shellcheck source=lib/recon_report.sh
source "$SCRIPT_DIR/lib/recon_report.sh"
main() {
printf '\033[1m%s - read-only device recon\033[0m\n' "$SCRIPT_NAME"

View File

@ -66,63 +66,10 @@ read_facts_value() {
printf '%s' "${line#*=}"
}
# dump_partition <partition> <destination>
#
# MTK_DUMP_CMD overrides the mtkclient invocation and is the seam the tests
# use: it is called as `$MTK_DUMP_CMD <partition> <destination>`. Without it
# the only way to exercise the manifest/verification logic below would be to
# attach a phone in BROM mode, so that code would ship unrun.
dump_partition() {
local partition="$1" dest="$2"
local mtk_dir="" python_bin=""
mtk_info "Dumping ${partition} -> ${dest}"
if [[ -n ${MTK_DUMP_CMD:-} ]]; then
# shellcheck disable=SC2086 # intentional word splitting: the override may
# carry arguments, e.g. MTK_DUMP_CMD="./stub.sh --size 4M"
${MTK_DUMP_CMD} "$partition" "$dest"
return $?
fi
mtk_dir="$(mtk_mtkclient_dir)"
python_bin="$(mtk_venv_python)"
mtk_info "mtkclient is waiting for the device in BROM/preloader mode."
mtk_info "Power the phone OFF, then connect USB (some units need vol- held)."
# `mtk.py r <partition> <outfile>` per the mtkclient README. Run from the
# clone directory because mtk.py resolves its Loader/ paths relative to cwd.
(
cd "$mtk_dir" || exit 1
"$python_bin" mtk.py r "$partition" "$dest"
)
}
verify_dump() {
local label="$1" path="$2"
local size="" verdict="" sha=""
if [[ ! -f $path ]]; then
mtk_error "${label}: no file produced at ${path}"
return 1
fi
size="$(mtk_file_size "$path")"
sha="$(mtk_sha256 "$path")"
if verdict="$(mtk_sane_ramdisk_size "$size")"; then
mtk_info "${label}: ${verdict}, sha256 ${sha}"
else
# mtkclient exits 0 on a truncated read, so size is the only signal that
# something went wrong short of parsing the image.
mtk_warn "${label}: ${verdict}"
mtk_warn "${label}: sha256 ${sha}"
mtk_warn "Inspect this image before trusting it as a backup."
return 1
fi
return 0
}
# shellcheck source=lib/dump_partitions.sh
source "$SCRIPT_DIR/lib/dump_partitions.sh"
# shellcheck source=lib/dump_verify.sh
source "$SCRIPT_DIR/lib/dump_verify.sh"
main() {
printf '\033[1m%s - stock partition dump (MediaTek only)\033[0m\n' "$SCRIPT_NAME"

View File

@ -12,7 +12,7 @@
set -euo pipefail
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
readonly SCRIPT_DIR
readonly SCRIPT_NAME="${0##*/}"
@ -99,129 +99,8 @@ ensure_groups() {
fi
}
install_udev() {
mtk_heading "udev rules"
if [[ ! -f $UDEV_SOURCE ]]; then
mtk_error "Missing rules source: ${UDEV_SOURCE}"
return 1
fi
if [[ -f $UDEV_TARGET ]] && sudo cmp -s "$UDEV_SOURCE" "$UDEV_TARGET"; then
mtk_info "Rules already current at ${UDEV_TARGET}"
else
mtk_info "Installing ${UDEV_TARGET}"
sudo install -m 0644 "$UDEV_SOURCE" "$UDEV_TARGET"
sudo udevadm control --reload-rules
sudo udevadm trigger
fi
if command -v udevadm >/dev/null 2>&1 && udevadm verify --help >/dev/null 2>&1; then
if udevadm verify "$UDEV_TARGET" >/dev/null 2>&1; then
mtk_info "udevadm verify: clean"
else
mtk_error "udevadm verify rejected ${UDEV_TARGET}"
return 1
fi
fi
handle_catchall
}
handle_catchall() {
local catchall=""
catchall="$(mtk_udev_catchall_files)"
[[ -z $catchall ]] && return 0
mtk_warn "World-writable catch-all udev rule found in:"
printf '%s\n' "$catchall" | sed 's/^/ /'
mtk_warn 'A rule matching idVendor=="*" with MODE="0666" grants every local'
mtk_warn 'process read/write access to EVERY USB device, not just phones.'
if [[ $FIX_UDEV -eq 0 ]]; then
mtk_warn "Not changing it. Another script may depend on it."
mtk_warn "To narrow it: ${SCRIPT_NAME} --fix-udev"
return 0
fi
local file="" stamp=""
stamp="$(date -u '+%Y%m%dT%H%M%SZ')"
while IFS= read -r file; do
[[ -n $file ]] || continue
mtk_info "Backing up ${file} -> ${file}.bak-${stamp}"
sudo cp -a "$file" "${file}.bak-${stamp}"
# Comment the offending line rather than deleting it, so the change is
# obvious and trivially reversible.
sudo sed -i -E 's|^([^#].*idVendor\}=="\*".*MODE="0666".*)$|# disabled by mtk_root install.sh --fix-udev: world-writable catch-all\n#\1|' "$file"
mtk_info "Commented catch-all in ${file}"
done <<<"$catchall"
sudo udevadm control --reload-rules
sudo udevadm trigger
}
setup_mtkclient() {
mtk_heading "mtkclient"
local clone_dir="" python_bin=""
clone_dir="$(mtk_mtkclient_dir)"
if [[ -d "$clone_dir/.git" ]]; then
mtk_info "Updating existing clone at ${clone_dir}"
git -C "$clone_dir" pull --ff-only || mtk_warn "Pull failed; continuing with current checkout."
else
mtk_info "Cloning ${MTKCLIENT_REPO}"
mkdir -p "$(dirname "$clone_dir")"
git clone --depth 1 "$MTKCLIENT_REPO" "$clone_dir"
fi
local rev=""
rev="$(git -C "$clone_dir" rev-parse --short HEAD 2>/dev/null || echo unknown)"
mtk_info "mtkclient at rev ${rev}"
# Rebuild the venv when it cannot import its dependencies. A Python upgrade
# orphans a venv while leaving it looking complete on disk - the venv found
# on this host in Aug 2026 failed exactly that way.
python_bin="$(mtk_venv_python)"
if ! mtk_check_venv >/dev/null 2>&1; then
if [[ -d "$clone_dir/venv" ]]; then
mtk_warn "Existing venv is unusable; rebuilding."
rm -rf "$clone_dir/venv"
fi
mtk_info "Creating venv with $(python3 -V 2>&1)"
python3 -m venv "$clone_dir/venv"
"$clone_dir/venv/bin/pip" install --upgrade pip
if [[ -f "$clone_dir/requirements.txt" ]]; then
"$clone_dir/venv/bin/pip" install -r "$clone_dir/requirements.txt"
else
# Newer mtkclient revisions ship a pyproject instead of requirements.txt.
mtk_info "No requirements.txt; installing the package itself."
"$clone_dir/venv/bin/pip" install "$clone_dir"
fi
else
mtk_info "venv already usable."
fi
local status=""
if status="$(mtk_check_venv)"; then
mtk_info "venv check: ${status}"
else
mtk_error "venv still unusable after install: ${status}"
mtk_error "Read ${clone_dir}/README.md - its install steps may have changed."
return 1
fi
}
prepare_cache() {
mtk_heading "Workspace"
local cache_dir=""
cache_dir="$(mtk_cache_dir)"
mkdir -p "$cache_dir" "$(mtk_stock_dir)"
mtk_info "Cache: ${cache_dir}"
mtk_info "Artifacts stay here, outside the repo - it rejects binaries, and"
mtk_info "factory images run to several GB."
}
# shellcheck source=lib/mtk_udev.sh
source "$SCRIPT_DIR/lib/mtk_udev.sh"
main() {
printf '\033[1m%s - host setup for the mtk_root toolkit\033[0m\n' "$SCRIPT_NAME"

View File

@ -0,0 +1,39 @@
#!/bin/bash
# Reading facts and dumping individual partitions.
#
# Sourced by 20-dump-stock.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# dump_partition <partition> <destination>
#
# MTK_DUMP_CMD overrides the mtkclient invocation and is the seam the tests
# use: it is called as `$MTK_DUMP_CMD <partition> <destination>`. Without it
# the only way to exercise the manifest/verification logic below would be to
# attach a phone in BROM mode, so that code would ship unrun.
dump_partition() {
local partition="$1" dest="$2"
local mtk_dir="" python_bin=""
mtk_info "Dumping ${partition} -> ${dest}"
if [[ -n ${MTK_DUMP_CMD:-} ]]; then
# shellcheck disable=SC2086 # intentional word splitting: the override may
# carry arguments, e.g. MTK_DUMP_CMD="./stub.sh --size 4M"
${MTK_DUMP_CMD} "$partition" "$dest"
return $?
fi
mtk_dir="$(mtk_mtkclient_dir)"
python_bin="$(mtk_venv_python)"
mtk_info "mtkclient is waiting for the device in BROM/preloader mode."
mtk_info "Power the phone OFF, then connect USB (some units need vol- held)."
# `mtk.py r <partition> <outfile>` per the mtkclient README. Run from the
# clone directory because mtk.py resolves its Loader/ paths relative to cwd.
(
cd "$mtk_dir" || exit 1
"$python_bin" mtk.py r "$partition" "$dest"
)
}

View File

@ -0,0 +1,31 @@
#!/bin/bash
# Dump verification and reporting for the stock partition dump.
#
# Sourced by 20-dump-stock.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
verify_dump() {
local label="$1" path="$2"
local size="" verdict="" sha=""
if [[ ! -f $path ]]; then
mtk_error "${label}: no file produced at ${path}"
return 1
fi
size="$(mtk_file_size "$path")"
sha="$(mtk_sha256 "$path")"
if verdict="$(mtk_sane_ramdisk_size "$size")"; then
mtk_info "${label}: ${verdict}, sha256 ${sha}"
else
# mtkclient exits 0 on a truncated read, so size is the only signal that
# something went wrong short of parsing the image.
mtk_warn "${label}: ${verdict}"
mtk_warn "${label}: sha256 ${sha}"
mtk_warn "Inspect this image before trusting it as a backup."
return 1
fi
return 0
}

View File

@ -0,0 +1,129 @@
#!/bin/bash
# udev rules and the mtkclient checkout for MediaTek rooting.
#
# Sourced by install.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
install_udev() {
mtk_heading "udev rules"
if [[ ! -f $UDEV_SOURCE ]]; then
mtk_error "Missing rules source: ${UDEV_SOURCE}"
return 1
fi
if [[ -f $UDEV_TARGET ]] && sudo cmp -s "$UDEV_SOURCE" "$UDEV_TARGET"; then
mtk_info "Rules already current at ${UDEV_TARGET}"
else
mtk_info "Installing ${UDEV_TARGET}"
sudo install -m 0644 "$UDEV_SOURCE" "$UDEV_TARGET"
sudo udevadm control --reload-rules
sudo udevadm trigger
fi
if command -v udevadm >/dev/null 2>&1 && udevadm verify --help >/dev/null 2>&1; then
if udevadm verify "$UDEV_TARGET" >/dev/null 2>&1; then
mtk_info "udevadm verify: clean"
else
mtk_error "udevadm verify rejected ${UDEV_TARGET}"
return 1
fi
fi
handle_catchall
}
handle_catchall() {
local catchall=""
catchall="$(mtk_udev_catchall_files)"
[[ -z $catchall ]] && return 0
mtk_warn "World-writable catch-all udev rule found in:"
printf '%s\n' "$catchall" | sed 's/^/ /'
mtk_warn 'A rule matching idVendor=="*" with MODE="0666" grants every local'
mtk_warn 'process read/write access to EVERY USB device, not just phones.'
if [[ $FIX_UDEV -eq 0 ]]; then
mtk_warn "Not changing it. Another script may depend on it."
mtk_warn "To narrow it: ${SCRIPT_NAME} --fix-udev"
return 0
fi
local file="" stamp=""
stamp="$(date -u '+%Y%m%dT%H%M%SZ')"
while IFS= read -r file; do
[[ -n $file ]] || continue
mtk_info "Backing up ${file} -> ${file}.bak-${stamp}"
sudo cp -a "$file" "${file}.bak-${stamp}"
# Comment the offending line rather than deleting it, so the change is
# obvious and trivially reversible.
sudo sed -i -E 's|^([^#].*idVendor\}=="\*".*MODE="0666".*)$|# disabled by mtk_root install.sh --fix-udev: world-writable catch-all\n#\1|' "$file"
mtk_info "Commented catch-all in ${file}"
done <<<"$catchall"
sudo udevadm control --reload-rules
sudo udevadm trigger
}
setup_mtkclient() {
mtk_heading "mtkclient"
local clone_dir=""
clone_dir="$(mtk_mtkclient_dir)"
if [[ -d "$clone_dir/.git" ]]; then
mtk_info "Updating existing clone at ${clone_dir}"
git -C "$clone_dir" pull --ff-only || mtk_warn "Pull failed; continuing with current checkout."
else
mtk_info "Cloning ${MTKCLIENT_REPO}"
mkdir -p "$(dirname "$clone_dir")"
git clone --depth 1 "$MTKCLIENT_REPO" "$clone_dir"
fi
local rev=""
rev="$(git -C "$clone_dir" rev-parse --short HEAD 2>/dev/null || echo unknown)"
mtk_info "mtkclient at rev ${rev}"
# Rebuild the venv when it cannot import its dependencies. A Python upgrade
# orphans a venv while leaving it looking complete on disk - the venv found
# on this host in Aug 2026 failed exactly that way.
if ! mtk_check_venv >/dev/null 2>&1; then
if [[ -d "$clone_dir/venv" ]]; then
mtk_warn "Existing venv is unusable; rebuilding."
rm -rf "$clone_dir/venv"
fi
mtk_info "Creating venv with $(python3 -V 2>&1)"
python3 -m venv "$clone_dir/venv"
"$clone_dir/venv/bin/pip" install --upgrade pip
if [[ -f "$clone_dir/requirements.txt" ]]; then
"$clone_dir/venv/bin/pip" install -r "$clone_dir/requirements.txt"
else
# Newer mtkclient revisions ship a pyproject instead of requirements.txt.
mtk_info "No requirements.txt; installing the package itself."
"$clone_dir/venv/bin/pip" install "$clone_dir"
fi
else
mtk_info "venv already usable."
fi
local status=""
if status="$(mtk_check_venv)"; then
mtk_info "venv check: ${status}"
else
mtk_error "venv still unusable after install: ${status}"
mtk_error "Read ${clone_dir}/README.md - its install steps may have changed."
return 1
fi
}
prepare_cache() {
mtk_heading "Workspace"
local cache_dir=""
cache_dir="$(mtk_cache_dir)"
mkdir -p "$cache_dir" "$(mtk_stock_dir)"
mtk_info "Cache: ${cache_dir}"
mtk_info "Artifacts stay here, outside the repo - it rejects binaries, and"
mtk_info "factory images run to several GB."
}

View File

@ -0,0 +1,112 @@
#!/bin/bash
# Partition, lock-state and manual-check reporting for MTK recon.
#
# Sourced by 10-recon.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# ---------------------------------------------------------------------------
# Reporting
# ---------------------------------------------------------------------------
report_partitions() {
local carrier=""
carrier="$(mtk_ramdisk_carrier)"
mtk_heading "Partitions"
printf ' A/B scheme : %s\n' "$MTK_AB_SCHEME"
if [[ ${MTK_SLOT_ASSUMED:-0} -eq 1 ]]; then
printf ' slot suffix : %s (ASSUMED - ro.boot.slot_suffix was empty)\n' "${MTK_SLOT_SUFFIX:-none}"
else
printf ' slot suffix : %s\n' "${MTK_SLOT_SUFFIX:-none}"
fi
printf ' ramdisk lives in: %s -> partition %s\n' "${carrier:-UNKNOWN}" "${MTK_RAMDISK_PART:-NONE FOUND}"
printf ' vbmeta : %s\n' "${MTK_VBMETA_PART:-NONE FOUND}"
# boot vs init_boot is the single most consequential fact here: patching the
# wrong one produces a device that does not boot.
if [[ $carrier == "init_boot" ]]; then
printf ' => Magisk must patch INIT_BOOT on this device.\n'
elif [[ $carrier == "boot" ]]; then
printf ' => Magisk must patch BOOT on this device (no init_boot present).\n'
else
printf ' => Could not identify a ramdisk carrier. Do not flash anything.\n'
fi
mtk_check_layout_expectation || true
}
report_lock_state() {
mtk_heading "Lock state"
printf ' ro.boot.flash.locked : %s\n' "${UNLOCK_FLASH_LOCKED:-<unset>}"
printf ' ro.boot.verifiedbootstate : %s\n' "${UNLOCK_VBSTATE:-<unset>}"
printf ' ro.boot.vbmeta.device_state : %s\n' "${UNLOCK_DEVICE_STATE:-<unset>}"
printf ' sys.oem_unlock_allowed : %s\n' "${UNLOCK_SYS_ALLOWED:-<unset>}"
printf ' ro.oem_unlock_supported : %s\n' "${UNLOCK_OEM_SUPPORTED:-<unset>}"
printf ' settings oem_unlock_allowed : %s\n' "${UNLOCK_SETTING:-<unset>}"
printf '\n'
printf ' OEM-unlock toggle : %s\n' "$UNLOCK_TOGGLE"
printf ' Carrier lock : %s\n' "$(carrier_lock_verdict)"
printf '\n'
printf ' Carrier lock cannot be determined from any property. An unset\n'
printf ' sys.oem_unlock_allowed means the toggle is off, which is NOT the same\n'
printf ' as carrier-locked. Settle it out of band: check the IMEI with the\n'
printf ' carrier, or in the Google Store order record.\n'
}
report_manual_checks() {
mtk_heading "Check these on the phone screen yourself"
printf ' Settings > System > Developer options > "OEM unlocking":\n'
printf ' - toggleable => bootloader unlock is permitted by the firmware\n'
printf ' - greyed out => blocked (carrier policy, no network, or unsupported)\n'
printf ' A property can say the toggle is off; only the UI shows whether it\n'
printf ' CAN be turned on. That distinction decides the path.\n'
}
report_decision() {
mtk_heading "Decision summary"
# The companion document that defines paths A-D was not provided to the
# session that wrote this script, so the mapping below is inferred. Say so
# every run rather than let a plausible-looking verdict pass as authoritative.
printf ' \033[0;33mPATH SEMANTICS ARE ASSUMED\033[0m - the companion doc defining A/B/C/D was\n'
printf ' not available when this was written. Reconcile before acting.\n\n'
case "$MTK_DEVICE_CLASS" in
ULEFONE)
if [[ $UNLOCK_TOGGLE == "ON" ]]; then
printf ' => PATH A (Ulefone, OEM unlocking available)\n'
printf ' Next: ./20-dump-stock.sh --serial %s\n' "$MTK_SERIAL"
printf ' Then patch %s with Magisk and flash MANUALLY.\n' "${MTK_RAMDISK_PART:-<unknown>}"
else
printf ' => PATH A or B (Ulefone; toggle reads %s)\n' "$UNLOCK_TOGGLE"
printf ' Confirm the toggle on-screen before choosing.\n'
printf ' If greyed out => PATH B: fastboot unlock is blocked, leaving the\n'
printf ' mtkclient/BROM route, which is the untested one. Dump first:\n'
printf ' ./20-dump-stock.sh --serial %s\n' "$MTK_SERIAL"
fi
;;
PIXEL)
printf ' => PATH C or D (Pixel) - INDETERMINATE\n'
printf ' The toggle reads %s and carrier lock is UNDETERMINED, so C and D\n' "$UNLOCK_TOGGLE"
printf ' cannot be told apart from properties alone.\n\n'
printf ' \033[0;31mThis toolkit will not act on a Pixel.\033[0m It is the daily driver;\n'
printf ' recon only. No dump, unlock, or flash step here targets it.\n'
;;
*)
printf ' => NO PATH. Device did not classify.\n'
printf ' %s\n' "$MTK_CLASS_REASON"
printf ' Refusing to guess. Run --explain-classification, and if this is\n'
printf ' genuinely the Ulefone, widen the patterns at the top of\n'
printf ' lib/mtk_common.sh.\n'
;;
esac
mtk_heading "Still unknown"
printf ' - Whether the OEM unlocking toggle can be enabled (needs the screen)\n'
printf ' - Carrier lock status (needs an out-of-band IMEI check)\n'
if [[ $MTK_DEVICE_CLASS == "ULEFONE" ]]; then
printf ' - Whether this unit BROM is open or SLA/DAA-locked (needs mtkclient)\n'
printf ' - Whether fastboot flashing unlock is enabled in this firmware build\n'
fi
}

View File

@ -0,0 +1,191 @@
#!/bin/bash
# Browser wrapper install, desktop-entry redirect, auto-update units and
# service enablement for the periodic system setup.
#
# Sourced by setup_periodic_system.sh; split out to keep it under the
# 250-line cap. Sourced rather than run, so it inherits the caller's strict
# mode and the variables defined above the source line.
# Function to install browser pre-exec wrapper and wire common browser names
install_browser_preexec_wrapper() {
echo ""
echo "6.1 Installing Browser Pre-Exec Wrapper..."
echo "========================================="
local wrapper="/usr/local/bin/browser-preexec-wrapper"
sed -e "s|__HOSTS_INSTALL_SCRIPT__|$HOSTS_INSTALL_SCRIPT|g" \
"$TEMPLATE_BROWSER_WRAPPER" > "$wrapper"
chmod +x "$wrapper"
echo "✓ Installed wrapper: $wrapper"
# Allow passwordless execution of hosts installer for root-only actions
local sudoers_file="/etc/sudoers.d/hosts-install-no-passwd"
if command -v visudo > /dev/null 2>&1; then
echo "${SUDO_USER:-$USER} ALL=(ALL) NOPASSWD: $HOSTS_INSTALL_SCRIPT" > "$sudoers_file"
chmod 440 "$sudoers_file"
# Validate syntax
visudo -c > /dev/null || echo "Warning: sudoers validation returned non-zero"
echo "✓ Sudoers drop-in created: $sudoers_file"
else
echo "visudo not found; skipping sudoers drop-in"
fi
# Create symlinks for common browser commands to the wrapper in /usr/local/bin
# This takes precedence over /usr/bin in PATH on most systems.
local browsers=("thorium-browser" "google-chrome" "google-chrome-stable" "chromium" "brave" "brave-browser" "vivaldi-stable" "firefox")
for b in "${browsers[@]}"; do
local link="/usr/local/bin/$b"
ln -sf "$wrapper" "$link"
done
echo "✓ Symlinked wrapper for common browsers in /usr/local/bin"
redirect_app_mode_desktop_entries
}
# Chromium "app mode" shortcuts (--app-id=...) are auto-generated with a direct
# Exec=/opt/<browser>/<browser> line, bypassing /usr/local/bin entirely. That
# means neither the flags file nor the crash logging applies to them, and it is
# silent: on 2026-08-09 five such Thorium entries were found still launching
# without the --disable-gpu-compositing mitigation added on 2026-07-25.
# Chromium regenerates these files, so this re-runs on every install.
redirect_app_mode_desktop_entries() {
local target_user="${SUDO_USER:-$USER}"
local apps_dir
apps_dir="$(getent passwd "$target_user" | cut -d: -f6)/.local/share/applications"
[[ -d $apps_dir ]] || return 0
local rewritten=0 f
while IFS= read -r -d '' f; do
if grep -q '^Exec=/opt/' "$f"; then
# Keep only the BASENAME, whatever the nesting depth:
# /opt/thorium-browser/thorium-browser -> /usr/local/bin/thorium-browser
# /opt/google/chrome/google-chrome -> /usr/local/bin/google-chrome
# The greedy .* up to the last slash is what makes depth irrelevant;
# matching a single path segment silently mangles the nested case.
sed -i -E 's|^Exec=/opt/.*/([^/ ]+)|Exec=/usr/local/bin/\1|' "$f"
rewritten=$((rewritten + 1))
fi
done < <(find "$apps_dir" -maxdepth 1 -type f -name '*.desktop' -print0 2> /dev/null)
if ((rewritten > 0)); then
chown "$target_user" "$apps_dir"/*.desktop 2> /dev/null || true
echo "✓ Redirected $rewritten app-mode .desktop entries through the wrapper"
else
echo "✓ No app-mode .desktop entries needed redirecting"
fi
}
# Function to install automatic system update service
install_auto_update() {
echo ""
echo "6.2 Installing Automatic System Update..."
echo "========================================="
local update_script="/usr/local/bin/auto-system-update.sh"
local update_service="/etc/systemd/system/auto-system-update.service"
local update_timer="/etc/systemd/system/auto-system-update.timer"
# Install script from template with user substitution
local actual_user="${SUDO_USER:-$USER}"
sed -e "s|__ACTUAL_USER__|$actual_user|g" \
"$TEMPLATE_AUTO_UPDATE" > "$update_script"
chmod +x "$update_script"
echo "✓ Installed auto-update script: $update_script (user: $actual_user)"
# Install systemd service and timer from templates
install -m 0644 "$TEMPLATE_AUTO_UPDATE_SVC" "$update_service"
echo "✓ Installed auto-update service: $update_service"
install -m 0644 "$TEMPLATE_AUTO_UPDATE_TIMER" "$update_timer"
echo "✓ Installed auto-update timer: $update_timer"
}
# Function to enable and start services
enable_services() {
echo ""
echo "7. Enabling Services and Timer..."
echo "================================="
# Reload systemd daemon
systemctl daemon-reload
echo "✓ Systemd daemon reloaded"
# Enable and start the timer
systemctl enable periodic-system-maintenance.timer
systemctl start periodic-system-maintenance.timer
echo "✓ Timer enabled and started"
# Enable startup service (but don't start it now)
systemctl enable periodic-system-startup.service
echo "✓ Startup service enabled"
# Enable hosts file monitor service
systemctl enable hosts-file-monitor.service
systemctl start hosts-file-monitor.service
echo "✓ Hosts file monitor service enabled and started"
# Enable and start auto-update timer
systemctl enable auto-system-update.timer
systemctl start auto-system-update.timer
echo "✓ Auto-update timer enabled and started"
# Show timer status
echo ""
echo "Timer Status:"
systemctl status periodic-system-maintenance.timer --no-pager -l
echo ""
echo "Auto-Update Timer Status:"
systemctl status auto-system-update.timer --no-pager -l
echo ""
echo "Hosts Monitor Status:"
systemctl status hosts-file-monitor.service --no-pager -l
echo ""
echo "Next scheduled runs:"
systemctl list-timers periodic-system-maintenance.timer auto-system-update.timer --no-pager
}
# Function to create log rotation configuration
create_log_rotation() {
echo ""
echo "8. Setting up Log Rotation..."
echo "============================="
local logrotate_conf="/etc/logrotate.d/periodic-system-maintenance"
install -m 0644 "$TEMPLATE_LOGROTATE" "$logrotate_conf"
echo "✓ Installed log rotation configuration from template: $logrotate_conf"
}
# Function to run initial execution
run_initial_execution() {
echo ""
echo "9. Running Initial Execution..."
echo "==============================="
local run_initial=true
if [[ $INTERACTIVE_MODE == "true" ]]; then
echo "Would you like to run the system maintenance now to test the setup?"
read -p "Run initial execution? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
run_initial=false
fi
else
echo "Auto-running initial execution to test the setup (use --interactive to prompt)"
fi
if [[ $run_initial == "true" ]]; then
echo "Running initial system maintenance..."
/usr/local/bin/periodic-system-maintenance.sh
echo "✓ Initial execution completed"
else
echo "Skipping initial execution"
fi
}
# Main execution

View File

@ -172,189 +172,9 @@ create_hosts_monitor_service() {
echo "✓ Installed hosts monitor service from template: $monitor_service"
}
# Function to install browser pre-exec wrapper and wire common browser names
install_browser_preexec_wrapper() {
echo ""
echo "6.1 Installing Browser Pre-Exec Wrapper..."
echo "========================================="
# shellcheck source=lib/periodic_browser.sh
source "$SCRIPT_DIR/lib/periodic_browser.sh"
local wrapper="/usr/local/bin/browser-preexec-wrapper"
sed -e "s|__HOSTS_INSTALL_SCRIPT__|$HOSTS_INSTALL_SCRIPT|g" \
"$TEMPLATE_BROWSER_WRAPPER" > "$wrapper"
chmod +x "$wrapper"
echo "✓ Installed wrapper: $wrapper"
# Allow passwordless execution of hosts installer for root-only actions
local sudoers_file="/etc/sudoers.d/hosts-install-no-passwd"
if command -v visudo > /dev/null 2>&1; then
echo "${SUDO_USER:-$USER} ALL=(ALL) NOPASSWD: $HOSTS_INSTALL_SCRIPT" > "$sudoers_file"
chmod 440 "$sudoers_file"
# Validate syntax
visudo -c > /dev/null || echo "Warning: sudoers validation returned non-zero"
echo "✓ Sudoers drop-in created: $sudoers_file"
else
echo "visudo not found; skipping sudoers drop-in"
fi
# Create symlinks for common browser commands to the wrapper in /usr/local/bin
# This takes precedence over /usr/bin in PATH on most systems.
local browsers=("thorium-browser" "google-chrome" "google-chrome-stable" "chromium" "brave" "brave-browser" "vivaldi-stable" "firefox")
for b in "${browsers[@]}"; do
local link="/usr/local/bin/$b"
ln -sf "$wrapper" "$link"
done
echo "✓ Symlinked wrapper for common browsers in /usr/local/bin"
redirect_app_mode_desktop_entries
}
# Chromium "app mode" shortcuts (--app-id=...) are auto-generated with a direct
# Exec=/opt/<browser>/<browser> line, bypassing /usr/local/bin entirely. That
# means neither the flags file nor the crash logging applies to them, and it is
# silent: on 2026-08-09 five such Thorium entries were found still launching
# without the --disable-gpu-compositing mitigation added on 2026-07-25.
# Chromium regenerates these files, so this re-runs on every install.
redirect_app_mode_desktop_entries() {
local target_user="${SUDO_USER:-$USER}"
local apps_dir
apps_dir="$(getent passwd "$target_user" | cut -d: -f6)/.local/share/applications"
[[ -d $apps_dir ]] || return 0
local rewritten=0 f
while IFS= read -r -d '' f; do
if grep -q '^Exec=/opt/' "$f"; then
# Keep only the BASENAME, whatever the nesting depth:
# /opt/thorium-browser/thorium-browser -> /usr/local/bin/thorium-browser
# /opt/google/chrome/google-chrome -> /usr/local/bin/google-chrome
# The greedy .* up to the last slash is what makes depth irrelevant;
# matching a single path segment silently mangles the nested case.
sed -i -E 's|^Exec=/opt/.*/([^/ ]+)|Exec=/usr/local/bin/\1|' "$f"
rewritten=$((rewritten + 1))
fi
done < <(find "$apps_dir" -maxdepth 1 -type f -name '*.desktop' -print0 2> /dev/null)
if ((rewritten > 0)); then
chown "$target_user" "$apps_dir"/*.desktop 2> /dev/null || true
echo "✓ Redirected $rewritten app-mode .desktop entries through the wrapper"
else
echo "✓ No app-mode .desktop entries needed redirecting"
fi
}
# Function to install automatic system update service
install_auto_update() {
echo ""
echo "6.2 Installing Automatic System Update..."
echo "========================================="
local update_script="/usr/local/bin/auto-system-update.sh"
local update_service="/etc/systemd/system/auto-system-update.service"
local update_timer="/etc/systemd/system/auto-system-update.timer"
# Install script from template with user substitution
local actual_user="${SUDO_USER:-$USER}"
sed -e "s|__ACTUAL_USER__|$actual_user|g" \
"$TEMPLATE_AUTO_UPDATE" > "$update_script"
chmod +x "$update_script"
echo "✓ Installed auto-update script: $update_script (user: $actual_user)"
# Install systemd service and timer from templates
install -m 0644 "$TEMPLATE_AUTO_UPDATE_SVC" "$update_service"
echo "✓ Installed auto-update service: $update_service"
install -m 0644 "$TEMPLATE_AUTO_UPDATE_TIMER" "$update_timer"
echo "✓ Installed auto-update timer: $update_timer"
}
# Function to enable and start services
enable_services() {
echo ""
echo "7. Enabling Services and Timer..."
echo "================================="
# Reload systemd daemon
systemctl daemon-reload
echo "✓ Systemd daemon reloaded"
# Enable and start the timer
systemctl enable periodic-system-maintenance.timer
systemctl start periodic-system-maintenance.timer
echo "✓ Timer enabled and started"
# Enable startup service (but don't start it now)
systemctl enable periodic-system-startup.service
echo "✓ Startup service enabled"
# Enable hosts file monitor service
systemctl enable hosts-file-monitor.service
systemctl start hosts-file-monitor.service
echo "✓ Hosts file monitor service enabled and started"
# Enable and start auto-update timer
systemctl enable auto-system-update.timer
systemctl start auto-system-update.timer
echo "✓ Auto-update timer enabled and started"
# Show timer status
echo ""
echo "Timer Status:"
systemctl status periodic-system-maintenance.timer --no-pager -l
echo ""
echo "Auto-Update Timer Status:"
systemctl status auto-system-update.timer --no-pager -l
echo ""
echo "Hosts Monitor Status:"
systemctl status hosts-file-monitor.service --no-pager -l
echo ""
echo "Next scheduled runs:"
systemctl list-timers periodic-system-maintenance.timer auto-system-update.timer --no-pager
}
# Function to create log rotation configuration
create_log_rotation() {
echo ""
echo "8. Setting up Log Rotation..."
echo "============================="
local logrotate_conf="/etc/logrotate.d/periodic-system-maintenance"
install -m 0644 "$TEMPLATE_LOGROTATE" "$logrotate_conf"
echo "✓ Installed log rotation configuration from template: $logrotate_conf"
}
# Function to run initial execution
run_initial_execution() {
echo ""
echo "9. Running Initial Execution..."
echo "==============================="
local run_initial=true
if [[ $INTERACTIVE_MODE == "true" ]]; then
echo "Would you like to run the system maintenance now to test the setup?"
read -p "Run initial execution? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
run_initial=false
fi
else
echo "Auto-running initial execution to test the setup (use --interactive to prompt)"
fi
if [[ $run_initial == "true" ]]; then
echo "Running initial system maintenance..."
/usr/local/bin/periodic-system-maintenance.sh
echo "✓ Initial execution completed"
else
echo "Skipping initial execution"
fi
}
# Main execution
verify_files
create_execution_script
create_systemd_service

View File

@ -110,244 +110,9 @@ install_dependencies() {
fi
}
create_password_file() {
local force=${1:-0}
if [[ -f $PASSWORD_FILE && $force -ne 1 ]]; then
log "Using existing VNC password file at $PASSWORD_FILE"
return
fi
if [[ -f $PASSWORD_FILE ]]; then
if ! prompt_yes_no "Regenerate the stored VNC password?"; then
log "Keeping existing password."
return
fi
fi
local password confirm generated=0
read -rsp "Enter VNC password (leave blank to auto-generate): " password
printf '\n'
if [[ -z $password ]]; then
generated=1
password=$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 8)
log "Generated VNC password: $password"
else
read -rsp "Confirm password: " confirm
printf '\n'
if [[ $password != "$confirm" ]]; then
die "Passwords do not match."
fi
fi
local tmp
tmp=$(mktemp)
x11vnc -storepasswd "$password" "$tmp" > /dev/null
install -m 600 "$tmp" "$PASSWORD_FILE"
rm -f "$tmp"
if ((generated == 0)); then
log "Password stored securely at $PASSWORD_FILE (hashed)."
else
log "Please write down the generated password; it will be needed on your Android device."
fi
}
create_env_file() {
if [[ -f $ENV_FILE ]]; then
return
fi
cat > "$ENV_FILE" << EOF
# control-from-mobile configuration
# Adjust these values if needed and rerun: systemctl --user restart $SERVICE_NAME
X11_DISPLAY="$DEFAULT_DISPLAY"
VNC_PORT="$DEFAULT_PORT"
# Use 127.0.0.1 to force SSH tunnel-only access, or 0.0.0.0 to expose on LAN.
VNC_BIND_ADDR="$DEFAULT_BIND_ADDR"
EOF
chmod 600 "$ENV_FILE"
}
create_runner_script() {
cat > "$RUNNER_FILE" << 'EOF'
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
CONFIG_DIR="$(dirname "$(readlink -f "$0")")"
PASSWORD_FILE="$CONFIG_DIR/vnc.pass"
ENV_FILE="$CONFIG_DIR/env"
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/control-from-mobile"
mkdir -p "$STATE_DIR"
if [[ ! -f "$PASSWORD_FILE" ]]; then
echo "Missing VNC password file at $PASSWORD_FILE" >&2
exit 1
fi
if [[ -f "$ENV_FILE" ]]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
fi
X11_DISPLAY="${X11_DISPLAY:-${DISPLAY:-:0}}"
VNC_PORT="${VNC_PORT:-5901}"
VNC_BIND_ADDR="${VNC_BIND_ADDR:-0.0.0.0}"
LOG_FILE="$STATE_DIR/x11vnc.log"
exec /usr/bin/x11vnc \
-display "$X11_DISPLAY" \
-rfbport "$VNC_PORT" \
-listen "$VNC_BIND_ADDR" \
-forever \
-shared \
-auth guess \
-rfbauth "$PASSWORD_FILE" \
-noxdamage \
-repeat \
-ncache 10 \
-ncache_cr \
-o "$LOG_FILE"
EOF
chmod 700 "$RUNNER_FILE"
}
create_service_file() {
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Expose X11 desktop over VNC for Android control
After=graphical-session.target
PartOf=graphical-session.target
[Service]
Type=simple
EnvironmentFile=$ENV_FILE
ExecStart=$RUNNER_FILE
Restart=on-failure
RestartSec=2
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=default.target
EOF
}
reload_user_daemon() {
systemctl --user daemon-reload
}
ensure_service_present() {
if [[ ! -f $SERVICE_FILE || ! -x $RUNNER_FILE ]]; then
die "Service files missing. Run: $SCRIPT_NAME setup"
fi
}
start_service() {
ensure_service_present
systemctl --user start "$SERVICE_NAME"
}
stop_service() {
systemctl --user stop "$SERVICE_NAME" || true
}
status_service() {
if systemctl --user is-active --quiet "$SERVICE_NAME"; then
log "Service is active."
else
log "Service is inactive."
fi
systemctl --user status "$SERVICE_NAME" --no-pager || true
}
enable_service() {
ensure_service_present
systemctl --user enable "$SERVICE_NAME"
}
disable_service() {
systemctl --user disable "$SERVICE_NAME" || true
}
show_info() {
ensure_service_present
# shellcheck disable=SC1090
[[ -f $ENV_FILE ]] && source "$ENV_FILE"
local port="${VNC_PORT:-$DEFAULT_PORT}"
local bind_addr="${VNC_BIND_ADDR:-$DEFAULT_BIND_ADDR}"
local display="${X11_DISPLAY:-$DEFAULT_DISPLAY}"
local is_active="inactive"
if systemctl --user is-active --quiet "$SERVICE_NAME"; then
is_active="active"
fi
log "Service status: $is_active"
log "Display: $display"
log "Listening address: $bind_addr"
log "VNC port: $port"
log "Password file: $PASSWORD_FILE"
local -a ip_list=()
if command -v hostname > /dev/null 2>&1; then
while IFS= read -r line; do
[[ -z $line ]] && continue
ip_list+=("$line")
done < <(hostname -I 2> /dev/null | tr ' ' '\n' | grep -E '^[0-9]' || true)
fi
if ((${#ip_list[@]} > 0)); then
log "Detected LAN IPs:"
for ip in "${ip_list[@]}"; do
printf ' - %s\n' "$ip"
done
else
warn "Could not detect LAN IPs."
fi
printf '\nRecommended Android clients (FOSS):\n'
printf ' • bVNC (available on F-Droid) — supports full control.\n'
printf ' • Termux + OpenSSH for establishing an SSH tunnel when exposing only on 127.0.0.1.\n'
printf '\nConnect via VNC:\n'
printf ' Host: <your-ip>\n Port: %s\n Password: <stored during setup>\n' "$port"
local qr_host
if ((${#ip_list[@]} > 0)); then
qr_host="${ip_list[0]}"
else
qr_host="$bind_addr"
if [[ $qr_host == "0.0.0.0" || $qr_host == "::" ]]; then
qr_host="127.0.0.1"
fi
warn "Using fallback host $qr_host for QR code; replace with an accessible IP if needed."
fi
if command -v qrencode > /dev/null 2>&1; then
printf '\nConnection QR (vnc://%s:%s):\n' "$qr_host" "$port"
qrencode -o - "vnc://$qr_host:$port" -t ASCII || true
else
warn "qrencode not found; reinstall qrencode to get QR codes."
fi
printf '\nFor encrypted access outside your LAN, use Termux on Android:\n'
printf ' ssh -L %s:localhost:%s <user>@<public-ip>\n' "$port" "$port"
printf 'Then point bVNC to 127.0.0.1:%s.\n' "$port"
}
uninstall_files() {
local purge_password=${1:-0}
stop_service
disable_service
rm -f "$SERVICE_FILE"
rm -f "$RUNNER_FILE"
rm -f "$ENV_FILE"
if ((purge_password)); then
rm -f "$PASSWORD_FILE"
log "Removed password file."
fi
reload_user_daemon
log "Removed generated files."
}
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/mobile_service.sh
source "$SCRIPT_DIR/lib/mobile_service.sh"
main() {
require_non_root

View File

@ -137,248 +137,8 @@ check_python_version() {
fi
}
# ---------- Git clone/update ----------
setup_repo() {
mkdir -p "$INSTALL_ROOT"
if [[ ! -d "$REPO_DIR/.git" ]]; then
log "Cloning unreal-mcp into $REPO_DIR"
if require_cmd git; then
git clone "$REPO_URL" "$REPO_DIR"
else
fail "git is required but not found after install"
fi
else
log "Repo exists at $REPO_DIR"
if [[ $FORCE_UPDATE == true ]]; then
log "Updating repo with --force-update"
git -C "$REPO_DIR" fetch origin
git -C "$REPO_DIR" reset --hard origin/main
git -C "$REPO_DIR" pull --rebase --autostash
else
log "Pulling latest changes"
git -C "$REPO_DIR" pull --rebase --autostash
fi
fi
# Ensure ownership for the real user when script ran via sudo
if [[ $EUID -eq 0 ]]; then
chown -R "$ACTUAL_USER:$ACTUAL_USER" "$INSTALL_ROOT"
fi
}
# ---------- Launcher ----------
install_launcher() {
local bin_dir="$USER_HOME/.local/bin"
local python_dir="$REPO_DIR/Python"
local launcher="$bin_dir/unreal-mcp-server"
mkdir -p "$bin_dir"
cat > "$launcher" << EOF
#!/bin/bash
set -euo pipefail
exec uv --directory "$python_dir" run unreal_mcp_server.py "\${1:-}" < /dev/null
EOF
chmod +x "$launcher"
if [[ $EUID -eq 0 ]]; then chown "$ACTUAL_USER:$ACTUAL_USER" "$launcher"; fi
log "Installed launcher: $launcher"
}
# ---------- VS Code: Continue MCP config ----------
configure_continue() {
if [[ $CONFIGURE_CONTINUE != true ]]; then
log "Skipping Continue config (--no-continue)"
return 0
fi
local cont_dir="$USER_HOME/.continue"
local cont_cfg="$cont_dir/config.json"
local python_dir="$REPO_DIR/Python"
mkdir -p "$cont_dir"
# Base JSON when no config exists
local tmp_file
tmp_file="$(mktemp)"
if [[ ! -f $cont_cfg ]]; then
cat > "$tmp_file" << JSON
{
"mcpServers": {
"unrealMCP": {
"command": "uv",
"args": ["--directory", "$python_dir", "run", "unreal_mcp_server.py"]
}
}
}
JSON
mv "$tmp_file" "$cont_cfg"
else
# Merge using jq: ensure .mcpServers exists, then set/overwrite unrealMCP
if ! require_cmd jq; then
fail "jq is required to merge ~/.continue/config.json"
fi
jq --arg dir "$python_dir" '
.mcpServers = (.mcpServers // {}) |
.mcpServers.unrealMCP = {
command: "uv",
args: ["--directory", $dir, "run", "unreal_mcp_server.py"]
}
' "$cont_cfg" > "$tmp_file" && mv "$tmp_file" "$cont_cfg"
fi
if [[ $EUID -eq 0 ]]; then chown "$ACTUAL_USER:$ACTUAL_USER" "$cont_cfg"; fi
log "Configured Continue MCP at: $cont_cfg"
}
# ---------- VS Code user MCP (native) ----------
configure_vscode_user_mcp() {
if [[ $CONFIGURE_VSCODE_USER != true ]]; then
log "Skipping VS Code user MCP config (--no-vscode)"
return 0
fi
if ! require_cmd jq; then
fail "jq is required to compose VS Code --add-mcp JSON and to parse profiles"
fi
local python_dir="$REPO_DIR/Python"
local json
json=$(jq -n --arg dir "$python_dir" '{name:"unrealMCP", command:"uv", args:["--directory", $dir, "run", "unreal_mcp_server.py"]}')
# Handle multiple VS Code variants if present
local candidates=(code code-insiders codium)
local found_any=false
for cli in "${candidates[@]}"; do
if ! command -v "$cli" > /dev/null 2>&1; then
continue
fi
found_any=true
log "Registering MCP server in VS Code user profile via: $cli --add-mcp"
if "$cli" --add-mcp "$json" > "/tmp/${cli}-add-mcp.log" 2>&1; then
log "[$cli] user profile: unrealMCP added/updated"
else
sed -n '1,200p' "/tmp/${cli}-add-mcp.log" || true
fail "[$cli] --add-mcp failed for user profile. Ensure your VS Code supports MCP or rerun with --no-vscode."
fi
# Detect profiles with 'unreal' (case-insensitive) and add there too
local data_dir=""
case "$cli" in
code)
data_dir="$USER_HOME/.config/Code"
;;
code-insiders)
data_dir="$USER_HOME/.config/Code - Insiders"
;;
codium)
data_dir="$USER_HOME/.config/VSCodium"
;;
esac
local profiles_json="$data_dir/User/profiles/profiles.json"
if [[ -f $profiles_json ]]; then
# Extract profile names matching /unreal/i
mapfile -t unreal_profiles < <(jq -r '.profiles // [] | .[] | .name // empty | select(test("unreal"; "i"))' "$profiles_json")
if [[ ${#unreal_profiles[@]} -gt 0 ]]; then
log "[$cli] Found profiles with 'unreal': ${unreal_profiles[*]}"
local name
for name in "${unreal_profiles[@]}"; do
log "[$cli] Adding unrealMCP to profile: $name"
if "$cli" --profile "$name" --add-mcp "$json" > "/tmp/${cli}-add-mcp-${name// /_}.log" 2>&1; then
log "[$cli] profile '$name': unrealMCP added/updated"
else
sed -n '1,200p' "/tmp/${cli}-add-mcp-${name// /_}.log" || true
fail "[$cli] --add-mcp failed for profile '$name'."
fi
done
else
log "[$cli] No VS Code profiles with 'unreal' in name"
fi
else
log "[$cli] Profiles file not found: $profiles_json (skipping profile-specific adds)"
fi
done
if [[ $found_any == false ]]; then
fail "VS Code CLI not found (code/code-insiders/codium). Install VS Code and ensure 'code' CLI is available, or run with --no-vscode to skip."
fi
}
# ---------- Unreal Plugin copy (optional) ----------
install_plugin_into_project() {
[[ -n $PROJECT_UPROJECT ]] || return 0
local upath="$PROJECT_UPROJECT"
if [[ -d $upath ]]; then
# Resolve .uproject in the provided directory
mapfile -t _uprojects < <(find "$upath" -maxdepth 1 -type f -name "*.uproject" 2> /dev/null || true)
if [[ ${#_uprojects[@]} -eq 0 ]]; then
fail "--project directory '$upath' contains no .uproject files"
elif [[ ${#_uprojects[@]} -gt 1 ]]; then
printf '[ERROR] Multiple .uproject files found in %s:\n' "$upath" >&2
printf ' - %s\n' "${_uprojects[@]}" >&2
fail "Please pass the specific .uproject path to --project"
else
upath="${_uprojects[0]}"
log "Resolved .uproject: $upath"
fi
elif [[ -f $upath ]]; then
true
else
fail "--project path does not exist: $upath"
fi
if [[ ${upath##*.} != "uproject" ]]; then
fail "--project must point to a .uproject file (got: $upath)"
fi
local proj_dir
proj_dir="$(cd "$(dirname "$upath")" && pwd)"
RESOLVED_PROJECT_DIR="$proj_dir"
local src_plugin="$REPO_DIR/MCPGameProject/Plugins/UnrealMCP"
local dst_plugin="$proj_dir/Plugins/UnrealMCP"
if [[ ! -d $src_plugin ]]; then
fail "Source plugin not found at $src_plugin (did repo layout change?)"
fi
mkdir -p "$proj_dir/Plugins"
log "Copying UnrealMCP plugin to project: $dst_plugin"
rsync -a --delete "$src_plugin/" "$dst_plugin/"
# Set ownership back to actual user if run as root
if [[ $EUID -eq 0 ]]; then chown -R "$ACTUAL_USER:$ACTUAL_USER" "$proj_dir/Plugins"; fi
log "Plugin installed. Enable it from Unreal Editor (Edit > Plugins) if needed."
}
# ---------- Summary ----------
print_summary() {
local python_dir="$REPO_DIR/Python"
local plugin_dest="N/A"
if [[ -n $RESOLVED_PROJECT_DIR ]]; then
plugin_dest="$RESOLVED_PROJECT_DIR/Plugins/UnrealMCP"
fi
cat << EOF
============================================
Unreal MCP setup complete
============================================
Repo: $REPO_DIR
Python dir: $python_dir
Launcher: $USER_HOME/.local/bin/unreal-mcp-server
VS Code (Continue) MCP configured: ${CONFIGURE_CONTINUE}
- File: $USER_HOME/.continue/config.json
- Server ID: unrealMCP
VS Code (User profile) MCP configured: ${CONFIGURE_VSCODE_USER}
- Command used: code --add-mcp '{"name":"unrealMCP", "command":"uv", "args":["--directory","$python_dir","run","unreal_mcp_server.py"]}'
Optional usage:
- Run server manually: unreal-mcp-server
- In VS Code with Continue installed, the unrealMCP server will auto-start when needed.
Unreal plugin:
- Source: MCPGameProject/Plugins/UnrealMCP
- If you provided --project, the plugin was copied to: $plugin_dest
- In the Unreal Editor: Edit > Plugins > search "UnrealMCP" and enable. Restart when prompted.
Notes:
- Ensure you have Unreal Engine 5.5+ installed.
- The Python server listens to the Unreal plugin on TCP port 55557 by default.
- For other MCP clients (Claude Desktop, Cursor, Windsurf), copy the JSON snippet from the repo README to their config locations.
EOF
}
# shellcheck source=lib/unreal_mcp_repo.sh
source "$SCRIPT_DIR/lib/unreal_mcp_repo.sh"
main() {
log "Installing prerequisites (Arch Linux)"

View File

@ -0,0 +1,157 @@
#!/bin/bash
# Certificate sync, stunnel and unit installation for the DoT resolver.
#
# Sourced by setup_dot_resolver.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
install_cert_sync() {
# Caddy renews on its own schedule; stunnel reads files from disk and must
# be told. A timer copies the current cert out of the container and
# reloads stunnel only when the content actually changed.
sudo install -d -m 700 "$CERT_DIR"
sudo tee "$SYNC_SCRIPT" >/dev/null <<EOF
#!/bin/bash
# Copy the Caddy-managed certificate for $DOMAIN out to stunnel.
# Generated by $SCRIPT_NAME - edit that instead.
set -euo pipefail
src="$(cert_source_dir)"
tmp="\$(mktemp -d)"
trap 'rm -rf "\$tmp"' EXIT
docker cp "$CADDY_CONTAINER:\$src/$DOMAIN.crt" "\$tmp/cert.pem"
docker cp "$CADDY_CONTAINER:\$src/$DOMAIN.key" "\$tmp/key.pem"
cat "\$tmp/cert.pem" "\$tmp/key.pem" >"\$tmp/combined.pem"
if ! cmp -s "\$tmp/combined.pem" "$CERT_DIR/combined.pem"; then
install -m 600 "\$tmp/combined.pem" "$CERT_DIR/combined.pem"
systemctl reload-or-restart stunnel-dot.service
echo "certificate updated for $DOMAIN"
fi
EOF
sudo chmod 755 "$SYNC_SCRIPT"
}
install_stunnel_conf() {
sudo tee "$STUNNEL_CONF" >/dev/null <<EOF
; DNS-over-TLS front end for the local dnsmasq blocklist.
; Generated by $SCRIPT_NAME - edit that instead.
foreground = yes
syslog = yes
[dns-over-tls]
accept = $BIND_ADDR:$DOT_PORT
connect = 127.0.0.1:53
cert = $CERT_DIR/combined.pem
; DoT is TLS 1.2+ only in practice; Android requires a publicly trusted cert.
sslVersionMin = TLSv1.2
EOF
}
install_units() {
sudo tee /etc/systemd/system/stunnel-dot.service >/dev/null <<EOF
[Unit]
Description=DNS-over-TLS front end for dnsmasq blocklist
After=network-online.target dnsmasq.service wg-quick@wg0.service
Wants=network-online.target
Requires=dnsmasq.service
; Binding to the WireGuard address fails if the interface is not up yet.
After=sys-devices-virtual-net-wg0.device
[Service]
ExecStart=/usr/bin/stunnel $STUNNEL_CONF
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
sudo tee /etc/systemd/system/dot-cert-sync.service >/dev/null <<EOF
[Unit]
Description=Copy the Caddy certificate for $DOMAIN to stunnel
[Service]
Type=oneshot
ExecStart=$SYNC_SCRIPT
EOF
sudo tee /etc/systemd/system/dot-cert-sync.timer >/dev/null <<EOF
[Unit]
Description=Daily certificate sync for the DoT resolver
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
}
open_firewall() {
# Binding to the WireGuard address is NOT sufficient on its own. The
# input chain has `policy drop` and admits only specific ports over wg0
# (ssh), so a DoT connection from the phone is dropped even though the
# tunnel itself is up and ICMP replies fine. That combination is
# confusing to debug -- ping works, the port does not -- so the rule is
# added explicitly, scoped to the tunnel interface.
if [[ "$BIND_ADDR" != "0.0.0.0" ]]; then
if command -v nft >/dev/null 2>&1 && sudo nft list table inet filter >/dev/null 2>&1; then
if sudo nft list table inet filter | grep -q "iifname \"wg0\" tcp dport $DOT_PORT"; then
log "nftables already permits $DOT_PORT on wg0"
else
sudo nft add rule inet filter input iifname wg0 tcp dport "$DOT_PORT" accept ||
log "WARNING: could not add nftables rule for $DOT_PORT on wg0"
log "Permitted TCP $DOT_PORT on wg0 only"
fi
fi
log "No router port-forward needed - $BIND_ADDR is WireGuard-only."
return
fi
if command -v nft >/dev/null 2>&1 && sudo nft list table inet filter >/dev/null 2>&1; then
if ! sudo nft list table inet filter | grep -q "dport $DOT_PORT"; then
# Rate limited, because a publicly bound DoT endpoint is an open
# resolver: TCP-only so not usable for classic UDP amplification,
# but still someone else's free DNS and a standing attack surface.
# A phone issues a handful of lookups a second at worst; 25/second
# with a burst of 50 is far above real use and far below abuse.
sudo nft add rule inet filter input tcp dport "$DOT_PORT" \
limit rate 25/second burst 50 packets accept ||
log "WARNING: could not add rate-limited nftables rule for $DOT_PORT"
log "Permitted TCP $DOT_PORT (rate limited 25/s, burst 50)"
fi
fi
log "Ensure your router forwards TCP $DOT_PORT to this host."
}
run_check() {
local ok=0
systemctl is-active --quiet stunnel-dot.service ||
{
log "FAIL stunnel-dot.service not active"
ok=1
}
ss -lnt 2>/dev/null | grep -qE ":$DOT_PORT\b" ||
{
log "FAIL nothing listening on $DOT_PORT"
ok=1
}
# $CERT_DIR is mode 700 and owned by root because it holds a private key,
# so an unprivileged [[ -s ]] reports "missing" for a file that is
# present. Test as root, or --check reports a false failure on a healthy
# install.
sudo test -s "$CERT_DIR/combined.pem" ||
{
log "FAIL certificate missing at $CERT_DIR/combined.pem"
ok=1
}
if command -v kdig >/dev/null 2>&1; then
kdig +tls "@$BIND_ADDR" -p "$DOT_PORT" +short example.com >/dev/null 2>&1 ||
{
log "FAIL DoT query did not answer"
ok=1
}
fi
[[ $ok -eq 0 ]] && log "OK - DoT resolver healthy on $DOMAIN:$DOT_PORT"
return "$ok"
}

View File

@ -0,0 +1,221 @@
#!/bin/bash
# dwm config install, healing and the patch applications.
#
# Sourced by setup_dwm.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# ---------------------------------------------------------------------------
# 3. Install our versioned config.h onto the fresh upstream clone. dwm.c stays
# pristine here — movestack()/togglefullscr() are defined inside config.h, so
# only the two intentional behaviour changes below patch dwm.c.
# ---------------------------------------------------------------------------
install_config() {
log "Installing config.h from the repo (${REPO_DWM_DIR}/config.h)…"
cp -- "${REPO_DWM_DIR}/config.h" "$SRC_DIR/config.h"
}
# ---------------------------------------------------------------------------
# 3b. Auto-merge bleeding-edge config churn. When upstream adds a new config
# knob (e.g. `refreshrate`), dwm.c starts referencing a symbol our
# hand-written config.h doesn't define, breaking the build. To keep
# "always latest master" sustainable, copy across any scalar knob that the
# current dwm.c needs but our config.h lacks, using upstream's default.
# Only single-line scalars referenced by dwm.c are merged (arrays we own
# and unused symbols are left alone), so our customisations always win.
# ---------------------------------------------------------------------------
heal_config() {
local defh="$SRC_DIR/config.def.h" cfgh="$SRC_DIR/config.h" dwmc="$SRC_DIR/dwm.c"
[[ -f "$defh" && -f "$dwmc" ]] || return 0
local line name added=0
while IFS= read -r line; do
name="$(sed -nE 's/^.*[^A-Za-z0-9_]([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=.*/\1/p' <<<"$line")"
[[ -n "$name" ]] || continue
grep -qw "$name" "$cfgh" && continue # we already define it — keep ours
grep -qw "$name" "$dwmc" || continue # dwm.c doesn't need it — skip
printf '%s\n' "$line" >>"$cfgh"
warn "config.h: auto-merged new upstream knob '$name' (bleeding-edge churn)"
added=1
done < <(grep -E '^[[:space:]]*static[[:space:]]+const[[:space:]]+[^={]*=[^;{]*;' "$defh")
((added)) && log "Merged upstream config symbol(s) into config.h for this build."
return 0
}
# ---------------------------------------------------------------------------
# 3c. Focus-on-click: stop the pointer from changing focus / switching monitors.
# dwm defaults to focus-follows-mouse — and worse, crossing the screen
# boundary over EMPTY space (motionnotify) switches the active monitor, which
# yanks focus away from a fullscreen game on the other screen (no window edge
# to stop the pointer). We rewrite enternotify + motionnotify to no-ops so
# focus only changes on a CLICK or via the Mod+,/. (Mod+Ctrl+arrows) keys.
# Applied as an idempotent source rewrite after each reset so it survives the
# bleeding-edge `git pull`. perl -0777 slurps the file so the multi-line
# function bodies match at once (.*? stops at the first column-0 `}`, i.e. the
# function's own closing brace — nested if-block braces are tab-indented).
# The dwm/patches/focus-on-click.patch file is the human-readable equivalent.
# If upstream refactors these handlers the rewrite no-ops and we warn loudly
# rather than silently dropping the behaviour.
# ---------------------------------------------------------------------------
apply_focusonclick() {
local src="$SRC_DIR/dwm.c"
[[ -f "$src" ]] || return 0
perl -0777 -i -pe '
s!\nenternotify\(XEvent \*e\)\n\{.*?\n\}\n!\nenternotify(XEvent *e)\n{\n\t/* focusonclick: pointer never changes focus; use a click or Mod+keys. */\n\t(void)e;\n}\n!s;
s!\nmotionnotify\(XEvent \*e\)\n\{.*?\n\}\n!\nmotionnotify(XEvent *e)\n{\n\t/* focusonclick: keep the active monitor fixed when crossing screens. */\n\t(void)e;\n}\n!s;
' "$src"
# Verify both rewrites landed; warn (never abort) if upstream changed shape.
local ok=1
grep -q 'focusonclick: pointer never changes focus' "$src" || ok=0
grep -q 'focusonclick: keep the active monitor fixed' "$src" || ok=0
if ((ok)); then
log "Applied focus-on-click (pointer no longer changes focus or switches monitors)."
else
warn "focus-on-click rewrite did NOT match upstream dwm.c — pointer focus unchanged."
warn "enternotify/motionnotify were likely refactored upstream; update dwm/patches."
fi
return 0
}
# ---------------------------------------------------------------------------
# 3d. Auto pointer-confinement on fullscreen. dwm has no pointer barriers, so on
# a dual-monitor setup the cursor slides off a fullscreen game onto the other
# screen (there is no window edge to stop it). We hook setfullscreen() to
# start the `pointer-confine` helper (XFixes barriers) when a window goes
# fullscreen and stop it when fullscreen ends; unmanage() also stops it so a
# game that closes WHILE fullscreen can never leave the cursor trapped. The
# hook is a quick `if (system(...)) {}` — the `if` consumes system()'s result
# so -Wall stays warning-free; the trailing `&` returns to dwm immediately.
# Reapplied after each reset (idempotent via git) and self-verifying; the
# dwm/patches/fullscreen-pointer-confine.patch file mirrors it for reading.
# ---------------------------------------------------------------------------
apply_fullscreen_confine_hook() {
local src="$SRC_DIR/dwm.c"
[[ -f "$src" ]] || return 0
perl -0777 -i -pe '
s!(\n\t\tc->isfullscreen = 1;\n)!$1\t\tif (system("pconfine-auto on &")) {}\n!;
s!(\n\t\tc->isfullscreen = 0;\n)!$1\t\tif (system("pconfine-auto off &")) {}\n!;
s!(\nunmanage\(Client \*c, int destroyed\)\n\{\n\tMonitor \*m = c->mon;\n\tXWindowChanges wc;\n)!$1\tif (c->isfullscreen) { if (system("pconfine-auto off &")) {} }\n!;
' "$src"
# Expect: 1 "on", 2 "off" (setfullscreen-leave + unmanage). Warn if not.
local on off
on=$(grep -c 'pconfine-auto on' "$src")
off=$(grep -c 'pconfine-auto off' "$src")
if [[ "$on" == 1 && "$off" == 2 ]]; then
log "Applied auto pointer-confinement hook (locks the cursor to a fullscreen window's screen)."
else
warn "pointer-confine hook only partially applied (on=$on off=$off, expected 1/2)."
warn "setfullscreen/unmanage were likely refactored upstream; update dwm/patches."
fi
return 0
}
# ---------------------------------------------------------------------------
# 4. Build & install (PREFIX defaults to /usr/local).
# ---------------------------------------------------------------------------
build_install() {
log "Compiling dwm…"
make -C "$SRC_DIR" clean >/dev/null
make -C "$SRC_DIR" 2>&1 | tail -15
log "Installing dwm (sudo make install)…"
sudo make -C "$SRC_DIR" install 2>&1 | tail -8
}
# ---------------------------------------------------------------------------
# 4b. Build & install the pointer-confine helper (XFixes barriers) from the
# versioned dwm/pointer-confine.c. Standalone C so it stays out of dwm.c;
# dwm only spawns it via the setfullscreen() hook. If the X dev headers are
# missing it fails soft: warn and skip, leaving the rest of dwm fully working
# (fullscreen just won't auto-lock the cursor).
# ---------------------------------------------------------------------------
build_pointer_confine() {
log "Compiling pointer-confine from the repo (${REPO_DWM_DIR}/pointer-confine.c)…"
local bin
bin="$(mktemp)"
if cc -std=c99 -pedantic -Wall -O2 "${REPO_DWM_DIR}/pointer-confine.c" -o "$bin" \
-lX11 -lXfixes -lXinerama 2>/tmp/pointer-confine-build.log; then
sudo install -m 755 "$bin" "$BIN_CONFINE"
log "Installed $BIN_CONFINE."
else
warn "pointer-confine failed to compile — fullscreen cursor-lock disabled (dwm itself is fine):"
sed 's/^/ /' /tmp/pointer-confine-build.log >&2 || true
fi
rm -f "$bin"
}
# ---------------------------------------------------------------------------
# 5. Install the helper scripts (from the repo) and register the lightdm
# xsession. The scripts are the versioned files in dwm/bin/; we just place
# them on PATH with the right mode.
# ---------------------------------------------------------------------------
write_session_files() {
log "Installing helper scripts from the repo and the lightdm xsession entry…"
sudo install -m 755 "${REPO_DWM_DIR}/bin/dwm-session" "$BIN_SESSION"
sudo install -m 755 "${REPO_DWM_DIR}/bin/dwmstatus" "$BIN_STATUS"
sudo install -m 755 "${REPO_DWM_DIR}/bin/dwm-rebuild" "$BIN_REBUILD"
sudo install -m 755 "${REPO_DWM_DIR}/bin/switch-wm" "$BIN_SWITCH"
sudo install -m 755 "${REPO_DWM_DIR}/bin/pconfine-auto" "$BIN_CONFINE_AUTO"
# --- xsession entry for lightdm (absolute Exec path) --------------------
sudo tee "$XSESSION" >/dev/null <<'DESKTOP_EOF'
[Desktop Entry]
Name=dwm (i3-like)
Comment=dynamic window manager, compiled from source
Exec=/usr/local/bin/dwm-session
TryExec=/usr/local/bin/dwm
Type=Application
DesktopNames=dwm
DESKTOP_EOF
}
# ---------------------------------------------------------------------------
# 6. Verify the build links and the session is registered.
# ---------------------------------------------------------------------------
verify() {
log "Verifying install…"
local ver
ver="$(dwm -v 2>&1)" || true # dwm -v prints version then exit(1)
log "dwm version: ${ver:-<none>}"
command -v dwm >/dev/null && log "dwm binary: $(command -v dwm)"
[[ -f "$XSESSION" ]] && log "xsession registered: $XSESSION"
}
print_summary() {
cat <<SUMMARY
dwm is installed alongside i3 (i3 untouched).
This machine autologins (no session picker), so choose the WM you boot into:
switch-wm dwm -> boot dwm switch-wm i3 -> boot i3 switch-wm -> show
then reboot. Recovery if dwm misbehaves: TTY (Ctrl+Alt+F3) -> 'switch-wm i3' -> reboot.
Key bindings (Mod = Super):
Mod+Return terminator Mod+d dmenu
Mod+j / Mod+k focus next / prev Mod+Shift+j/k move in stack
Mod+h / Mod+l shrink / grow master Mod+i/Shift+i +/- master count
Mod+1..0 view tag 1..10 Mod+Shift+1..0 send to tag
Mod+f fullscreen Mod+Shift+space toggle floating
Mod+t / Mod+w tiling / monocle Mod+Shift+Return promote to master
Mod+Shift+q kill window Mod+Shift+e exit dwm
Mod+m mic mute Mod+Shift+r recompile (dwm-rebuild)
Two monitors (no i3-style per-output workspaces — see config.h note):
Mod+, / Mod+. focus the other screen (or Mod+Ctrl+Left/Right)
Mod+Shift+, / Mod+Shift+. throw window there (or Mod+Ctrl+Shift+L/R)
Focus-on-click is ON: the pointer no longer steals focus or switches monitors
when it crosses screens. Focus changes on click/keys.
Fullscreen cursor-lock is ON: when a window goes fullscreen (games), the cursor
is trapped on that screen (XFixes barriers) and released when fullscreen ends.
Stuck barrier? Mod+Shift+p force-releases it.
Status bar (clock, temps, load, RAM, volume) needs xsetroot:
sudo pacman -S xorg-xsetroot # then log out / back in
Preview it now without the bar: dwmstatus once
Customise (permanent): edit files in linux_configuration/dwm/ then re-run this
script. Quick experiment: edit ~/.local/src/dwm/config.h + run 'dwm-rebuild'
(re-running setup_dwm.sh overwrites it from the repo).
SUMMARY
}

View File

@ -0,0 +1,67 @@
#!/bin/bash
# Firewall, UPnP and router guidance for exposing Gitea.
#
# Sourced by setup_gitea.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
open_firewall() {
if [[ -x $WIREGUARD_SCRIPT ]]; then
sudo "$WIREGUARD_SCRIPT" allow-web
else
log_warn "Could not find ${WIREGUARD_SCRIPT} -- open tcp/80 and tcp/443 manually."
fi
}
attempt_upnp() {
has_cmd upnpc || {
log_warn "upnpc not installed -- skipping automatic port-forward attempt."
return 0
}
local lan_ip
lan_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')
[[ -n $lan_ip ]] || {
log_warn "Could not detect LAN IP -- skipping UPnP."
return 0
}
if upnpc -e "gitea-https" -a "$lan_ip" 443 443 tcp >/dev/null 2>&1 &&
upnpc -e "gitea-http" -a "$lan_ip" 80 80 tcp >/dev/null 2>&1; then
log_ok "UPnP port mapping succeeded for 80 and 443 -> ${lan_ip}."
else
log_warn "UPnP port mapping failed or unsupported by your router."
fi
}
print_router_instructions() {
local lan_ip
lan_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')
cat <<EOF
=== Manual step: verify port forwarding on your router (cannot be automated) ===
1. Log into your router admin page (often http://192.168.1.1).
2. Find "Port Forwarding" / "Virtual Server" / "NAT" settings.
3. Forward TCP 80 -> ${lan_ip}:80 and TCP 443 -> ${lan_ip}:443.
4. Save (and reboot the router if it requires it).
5. Confirm from OUTSIDE your LAN (e.g. phone on cellular data):
https://${GITEA_DOMAIN}
EOF
}
status_cmd() {
echo "=== Containers ==="
docker compose -f "$COMPOSE_FILE" ps 2>/dev/null || echo "(not deployed)"
echo
echo "=== Caddy certificate ==="
docker logs gitea-caddy 2>&1 | grep -i "certificate obtained" | tail -3 || echo "(no certificate log entry yet)"
}
usage() {
cat <<EOF
Usage: $0 <command>
Commands:
setup Full first-time setup (idempotent, safe to re-run).
status Show container and certificate status.
help Show this message.
EOF
}

View File

@ -0,0 +1,217 @@
#!/bin/bash
# Modelfile authoring and model pull for the local LLM.
#
# Sourced by setup_local_llm.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# ── 4. Create Modelfile with developer system prompt ─────────────────────────
create_modelfile() {
section "Creating custom model with developer system prompt"
# Condense Claude preferences into a system prompt (~1 K tokens).
# Note: hooks, skills, and Claude Code MCP tools do NOT port to local models.
# This only captures code-style, persona, and workflow preferences.
local modelfile
modelfile="$(mktemp --suffix=.modelfile)"
cat > "$modelfile" << MODELFILE_EOF
FROM ${MODEL}
PARAMETER num_ctx ${CTX_LEN}
PARAMETER temperature 0.6
PARAMETER top_p 0.95
PARAMETER top_k 20
SYSTEM """
You are a coding assistant for Krzysztof (kuhy) Rudnicki, a software developer
who maintains personal automation and app monorepos.
## About me
- Stack: Python, Bash, C/C++, TypeScript, Dart/Flutter, Go
- OS: Arch Linux, i3 window manager
- Key repos: testsAndMisc (automation), linux-configuration, praca_magisterska
## Code style
Python:
- Use from __future__ import annotations for forward refs
- Google docstring convention (triple-quoted, brief summary + Args/Returns)
- Absolute imports only, no relative imports
- Type hints required on every function signature
- Prefer typed dataclasses over plain dicts
Shell (bash):
- Always set -euo pipefail at the top
- Double-quote all variable expansions
- Avoid fork-heavy patterns: prefer /proc, /sys, bash builtins over \$(...)
in tight loops or status-bar scripts (fork-storm anti-pattern)
- Use jq/yq for JSON/YAML, not grep/awk
- NEVER embed multi-line Python logic inside shell heredocs — put it in a
separate .py file and invoke with python3 path/to/file.py
TypeScript:
- Target ES2022, pure ESM (no CommonJS require)
- No any — use unknown + narrowing
- Discriminated unions for state machines
- async/await + structured error handling
## Behaviour I expect
- Keep responses brief and direct — no filler preamble
- Ask before making high-impact changes (schema changes, deleting data)
- If you spot a bad approach, say so before complying
- Development order: implement → run to verify → confirm → tests
(tests are always LAST, not first)
- Include only one short comment per non-obvious block; no inline summaries
of what the code obviously does
## Testing rules
- 100% branch coverage required for Python packages
- Use pytest + coverage; never mock the filesystem in integration tests
- Shell scripts: shellcheck must pass with no suppressions
## Git workflow
- Commit directly to main (no branches for personal repo)
- Conventional commit format: type: brief description
- Always run pre-commit hooks before committing
"""
MODELFILE_EOF
local custom_model="${MODEL/:/-}-dev"
ollama create "$custom_model" -f "$modelfile"
rm -f "$modelfile"
ok "Custom model created: $custom_model (includes developer system prompt)"
ok "Load '$custom_model' in Open WebUI for kuhy-personalised responses"
}
# ── 5. Pull base model ────────────────────────────────────────────────────────
pull_model() {
section "Pulling ${MODEL}"
# Check if already present
if curl -sf "http://localhost:${OLLAMA_PORT}/api/tags" \
| grep -q "\"${MODEL}\""; then
ok "${MODEL} already downloaded"
return
fi
warn "Downloading ${MODEL} — approx 20 GB. This will take a while."
warn "Progress is shown live; do not interrupt."
ollama pull "${MODEL}"
ok "${MODEL} downloaded"
}
# ── 6. Set up Open WebUI via Docker ───────────────────────────────────────────
setup_webui() {
section "Setting up Open WebUI"
# Remove existing container so we can apply any config changes cleanly
if docker ps -a --format '{{.Names}}' | grep -qx "$WEBUI_CONTAINER"; then
warn "Removing existing $WEBUI_CONTAINER container..."
docker rm -f "$WEBUI_CONTAINER"
fi
docker pull ghcr.io/open-webui/open-webui:main
docker run -d \
--name "$WEBUI_CONTAINER" \
--restart always \
-p "${WEBUI_PORT}:8080" \
-v "${WEBUI_VOLUME}:/app/backend/data" \
-e OLLAMA_BASE_URL="http://host.docker.internal:${OLLAMA_PORT}" \
--add-host=host.docker.internal:host-gateway \
ghcr.io/open-webui/open-webui:main
ok "Open WebUI container started on port ${WEBUI_PORT}"
}
# ── 7. Enable Docker on boot ──────────────────────────────────────────────────
enable_autostart() {
section "Enabling auto-start on boot"
# Docker daemon must start for the container (restart=always) to come up
sudo systemctl enable docker
ok "docker.service enabled on boot"
ok "Ollama is already enabled; Open WebUI container uses restart=always"
}
# ── 8. Verify: GPU utilisation + generation speed ─────────────────────────────
verify_gpu() {
section "Verifying GPU utilisation and generation speed"
# Warm up with a short generation and measure tok/s
warn "Running a warm-up generation (checking GPU offload + speed)..."
local start_ts end_ts elapsed toks_per_sec
start_ts="$(date +%s%N)"
local response
response="$(curl -sf "http://localhost:${OLLAMA_PORT}/api/generate" \
-d "{\"model\":\"${MODEL}\",\"prompt\":\"Reply with exactly: ready\",\"stream\":false}" \
--max-time 120)"
end_ts="$(date +%s%N)"
elapsed=$(( (end_ts - start_ts) / 1000000 )) # milliseconds
if [[ -z "$response" ]]; then
err "No response from Ollama — generation failed"
return 1
fi
# Parse eval_count (output tokens) and eval_duration (nanoseconds) from response
local eval_count eval_duration_ns
eval_count="$(printf '%s' "$response" | grep -o '"eval_count":[0-9]*' | grep -o '[0-9]*' || echo 0)"
eval_duration_ns="$(printf '%s' "$response" | grep -o '"eval_duration":[0-9]*' | grep -o '[0-9]*' || echo 1)"
if (( eval_count > 0 && eval_duration_ns > 0 )); then
toks_per_sec=$(( eval_count * 1000000000 / eval_duration_ns ))
ok "Generation speed: ${toks_per_sec} tok/s (${eval_count} tokens in ${elapsed}ms)"
if (( toks_per_sec < 10 )); then
warn "Speed is below 10 tok/s — model may be partially CPU-offloaded"
warn "Run: ollama ps to check GPU layer count"
warn "If GPU% < 100, try reducing CTX_LEN in this script or use a smaller quant"
fi
else
warn "Could not parse tok/s from response; check manually with: ollama ps"
fi
# Check GPU offload via ollama ps
warn "Checking GPU layer utilisation..."
if command -v ollama &>/dev/null; then
ollama ps 2>/dev/null | head -10 || true
fi
ok "Verify done — see ollama ps output above for GPU% column"
}
# ── 9. WebUI readiness check ──────────────────────────────────────────────────
verify_webui() {
section "Waiting for Open WebUI to become ready"
wait_for_url "http://localhost:${WEBUI_PORT}" "Open WebUI" 60
}
# ── Summary ───────────────────────────────────────────────────────────────────
print_summary() {
local custom_model="${MODEL/:/-}-dev"
printf '\n\033[1;32m'
printf '═══════════════════════════════════════════════════════\n'
printf ' Local LLM setup complete!\n'
printf '═══════════════════════════════════════════════════════\n'
printf ' Open WebUI: http://localhost:%s\n' "$WEBUI_PORT"
printf ' Ollama API: http://localhost:%s\n' "$OLLAMA_PORT"
printf ' Primary model: %s (%d K context)\n' "$MODEL" $(( CTX_LEN / 1024 ))
printf ' Dev model: %s (with code-style system prompt)\n' "$custom_model"
printf '\n'
printf ' GPU fit notes:\n'
printf ' Current context: %d K (safe for 24 GB VRAM)\n' $(( CTX_LEN / 1024 ))
printf ' To try 24 K: edit CTX_LEN=24576 in this script\n'
printf ' To try 32 K: edit CTX_LEN=32768 (risks partial CPU offload)\n'
printf ' After changes: re-run this script; check tok/s in verify step\n'
printf '\n'
printf ' To use with Claude Code:\n'
printf ' Claude Code uses the Anthropic API — it cannot point at Ollama\n'
printf ' directly (different wire format). Use Open WebUI for local-model\n'
printf ' coding sessions, or ask about setting up a LiteLLM proxy.\n'
printf '═══════════════════════════════════════════════════════\n'
printf '\033[0m\n'
}
# ── Main ──────────────────────────────────────────────────────────────────────

View File

@ -0,0 +1,245 @@
#!/bin/bash
# Credential, env, runner and systemd unit generation.
#
# Sourced by control_from_mobile.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
create_password_file() {
local force=${1:-0}
if [[ -f $PASSWORD_FILE && $force -ne 1 ]]; then
log "Using existing VNC password file at $PASSWORD_FILE"
return
fi
if [[ -f $PASSWORD_FILE ]]; then
if ! prompt_yes_no "Regenerate the stored VNC password?"; then
log "Keeping existing password."
return
fi
fi
local password confirm generated=0
read -rsp "Enter VNC password (leave blank to auto-generate): " password
printf '\n'
if [[ -z $password ]]; then
generated=1
password=$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 8)
log "Generated VNC password: $password"
else
read -rsp "Confirm password: " confirm
printf '\n'
if [[ $password != "$confirm" ]]; then
die "Passwords do not match."
fi
fi
local tmp
tmp=$(mktemp)
x11vnc -storepasswd "$password" "$tmp" > /dev/null
install -m 600 "$tmp" "$PASSWORD_FILE"
rm -f "$tmp"
if ((generated == 0)); then
log "Password stored securely at $PASSWORD_FILE (hashed)."
else
log "Please write down the generated password; it will be needed on your Android device."
fi
}
create_env_file() {
if [[ -f $ENV_FILE ]]; then
return
fi
cat > "$ENV_FILE" << EOF
# control-from-mobile configuration
# Adjust these values if needed and rerun: systemctl --user restart $SERVICE_NAME
X11_DISPLAY="$DEFAULT_DISPLAY"
VNC_PORT="$DEFAULT_PORT"
# Use 127.0.0.1 to force SSH tunnel-only access, or 0.0.0.0 to expose on LAN.
VNC_BIND_ADDR="$DEFAULT_BIND_ADDR"
EOF
chmod 600 "$ENV_FILE"
}
create_runner_script() {
cat > "$RUNNER_FILE" << 'EOF'
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
CONFIG_DIR="$(dirname "$(readlink -f "$0")")"
PASSWORD_FILE="$CONFIG_DIR/vnc.pass"
ENV_FILE="$CONFIG_DIR/env"
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/control-from-mobile"
mkdir -p "$STATE_DIR"
if [[ ! -f "$PASSWORD_FILE" ]]; then
echo "Missing VNC password file at $PASSWORD_FILE" >&2
exit 1
fi
if [[ -f "$ENV_FILE" ]]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
fi
X11_DISPLAY="${X11_DISPLAY:-${DISPLAY:-:0}}"
VNC_PORT="${VNC_PORT:-5901}"
VNC_BIND_ADDR="${VNC_BIND_ADDR:-0.0.0.0}"
LOG_FILE="$STATE_DIR/x11vnc.log"
exec /usr/bin/x11vnc \
-display "$X11_DISPLAY" \
-rfbport "$VNC_PORT" \
-listen "$VNC_BIND_ADDR" \
-forever \
-shared \
-auth guess \
-rfbauth "$PASSWORD_FILE" \
-noxdamage \
-repeat \
-ncache 10 \
-ncache_cr \
-o "$LOG_FILE"
EOF
chmod 700 "$RUNNER_FILE"
}
create_service_file() {
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Expose X11 desktop over VNC for Android control
After=graphical-session.target
PartOf=graphical-session.target
[Service]
Type=simple
EnvironmentFile=$ENV_FILE
ExecStart=$RUNNER_FILE
Restart=on-failure
RestartSec=2
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=default.target
EOF
}
reload_user_daemon() {
systemctl --user daemon-reload
}
ensure_service_present() {
if [[ ! -f $SERVICE_FILE || ! -x $RUNNER_FILE ]]; then
die "Service files missing. Run: $SCRIPT_NAME setup"
fi
}
start_service() {
ensure_service_present
systemctl --user start "$SERVICE_NAME"
}
stop_service() {
systemctl --user stop "$SERVICE_NAME" || true
}
status_service() {
if systemctl --user is-active --quiet "$SERVICE_NAME"; then
log "Service is active."
else
log "Service is inactive."
fi
systemctl --user status "$SERVICE_NAME" --no-pager || true
}
enable_service() {
ensure_service_present
systemctl --user enable "$SERVICE_NAME"
}
disable_service() {
systemctl --user disable "$SERVICE_NAME" || true
}
show_info() {
ensure_service_present
# shellcheck disable=SC1090
[[ -f $ENV_FILE ]] && source "$ENV_FILE"
local port="${VNC_PORT:-$DEFAULT_PORT}"
local bind_addr="${VNC_BIND_ADDR:-$DEFAULT_BIND_ADDR}"
local display="${X11_DISPLAY:-$DEFAULT_DISPLAY}"
local is_active="inactive"
if systemctl --user is-active --quiet "$SERVICE_NAME"; then
is_active="active"
fi
log "Service status: $is_active"
log "Display: $display"
log "Listening address: $bind_addr"
log "VNC port: $port"
log "Password file: $PASSWORD_FILE"
local -a ip_list=()
if command -v hostname > /dev/null 2>&1; then
while IFS= read -r line; do
[[ -z $line ]] && continue
ip_list+=("$line")
done < <(hostname -I 2> /dev/null | tr ' ' '\n' | grep -E '^[0-9]' || true)
fi
if ((${#ip_list[@]} > 0)); then
log "Detected LAN IPs:"
for ip in "${ip_list[@]}"; do
printf ' - %s\n' "$ip"
done
else
warn "Could not detect LAN IPs."
fi
printf '\nRecommended Android clients (FOSS):\n'
printf ' • bVNC (available on F-Droid) — supports full control.\n'
printf ' • Termux + OpenSSH for establishing an SSH tunnel when exposing only on 127.0.0.1.\n'
printf '\nConnect via VNC:\n'
printf ' Host: <your-ip>\n Port: %s\n Password: <stored during setup>\n' "$port"
local qr_host
if ((${#ip_list[@]} > 0)); then
qr_host="${ip_list[0]}"
else
qr_host="$bind_addr"
if [[ $qr_host == "0.0.0.0" || $qr_host == "::" ]]; then
qr_host="127.0.0.1"
fi
warn "Using fallback host $qr_host for QR code; replace with an accessible IP if needed."
fi
if command -v qrencode > /dev/null 2>&1; then
printf '\nConnection QR (vnc://%s:%s):\n' "$qr_host" "$port"
qrencode -o - "vnc://$qr_host:$port" -t ASCII || true
else
warn "qrencode not found; reinstall qrencode to get QR codes."
fi
printf '\nFor encrypted access outside your LAN, use Termux on Android:\n'
printf ' ssh -L %s:localhost:%s <user>@<public-ip>\n' "$port" "$port"
printf 'Then point bVNC to 127.0.0.1:%s.\n' "$port"
}
uninstall_files() {
local purge_password=${1:-0}
stop_service
disable_service
rm -f "$SERVICE_FILE"
rm -f "$RUNNER_FILE"
rm -f "$ENV_FILE"
if ((purge_password)); then
rm -f "$PASSWORD_FILE"
log "Removed password file."
fi
reload_user_daemon
log "Removed generated files."
}

View File

@ -0,0 +1,143 @@
#!/bin/bash
# Caddy vhost, DuckDNS record and firewall rules for exposing SyncYomi.
#
# Sourced by setup_syncyomi.sh; split out to keep syncyomi_stack.sh under
# the 250-line cap. Sourced rather than run, so it inherits the caller's
# strict mode and the variables defined above the source line.
# --- Step 6: Caddy reverse-proxy block (append + reload) ---------------------
configure_caddy() {
if grep -qE "^${SYNCYOMI_SUBDOMAIN} \{" "${CADDYFILE}"; then
log_ok "Caddyfile already has a block for ${SYNCYOMI_SUBDOMAIN}"
else
log_info "Adding Caddy block for ${SYNCYOMI_SUBDOMAIN}"
# NOTE: appended to the shared Gitea Caddyfile. Re-running setup_gitea.sh
# regenerates that file and drops this block — re-run setup_syncyomi.sh
# to restore it. Caddyfile uses tab indentation.
printf '\n%s {\n\treverse_proxy 127.0.0.1:%s\n}\n' "${SYNCYOMI_SUBDOMAIN}" "${SYNCYOMI_PORT}" \
>>"${CADDYFILE}"
fi
docker exec "${CADDY_CONTAINER}" caddy reload --config "${CADDYFILE_IN_CONTAINER}" ||
die "caddy reload failed — check 'docker logs ${CADDY_CONTAINER}'."
log_ok "Caddy reloaded (auto-HTTPS will be issued once the subdomain resolves)"
}
# --- Step 7: DuckDNS subdomain (extend existing updater; no new cron) --------
configure_duckdns() {
local label="${SYNCYOMI_SUBDOMAIN%.duckdns.org}"
if grep -qE "domains=[^&\"']*${label}([,&\"']|$)" "${DUCKDNS_UPDATER}"; then
log_ok "DuckDNS updater already includes '${label}'"
else
log_info "Adding '${label}' to the existing DuckDNS updater"
sed -i -E "s|(domains=)([^&\"']*)|\1\2,${label}|" "${DUCKDNS_UPDATER}"
fi
# Refresh now (harmless if the subdomain isn't registered yet).
bash "${DUCKDNS_UPDATER}" >/dev/null 2>&1 || log_warn "DuckDNS update returned non-zero (register the subdomain first)."
if getent hosts "${SYNCYOMI_SUBDOMAIN}" >/dev/null 2>&1; then
log_ok "${SYNCYOMI_SUBDOMAIN} resolves"
else
log_warn "${SYNCYOMI_SUBDOMAIN} does not resolve yet — create the '${label}' subdomain in the DuckDNS dashboard."
fi
}
# --- Step 8: firewall (open 80/443 via the owning script, idempotent) -------
ensure_firewall() {
if sudo nft list ruleset 2>/dev/null | grep -qE 'dport \{[^}]*80[^}]*443'; then
log_ok "Firewall already allows tcp/80 + tcp/443"
elif [[ -f ${WG_SCRIPT} ]]; then
log_info "Opening 80/443 via setup_wireguard_ssh.sh allow-web"
sudo bash "${WG_SCRIPT}" allow-web
else
log_warn "setup_wireguard_ssh.sh not found — ensure tcp/80+443 are open."
fi
}
# --- Step 9: report ----------------------------------------------------------
print_report() {
local url="https://${SYNCYOMI_SUBDOMAIN}"
local key="(create one in the web UI)"
[[ -f ${TOKEN_FILE} ]] && key="$(<"${TOKEN_FILE}")"
cat <<EOF
============================================================================
SyncYomi is up.
Host address : ${url}
API key : ${key}
Web UI login : ${SYNCYOMI_USER} / (password in ${CONF_FILE})
TachiyomiSY setup (on the phone):
Settings → Data & storage → Sync → SyncYomi
Host : ${url}
API key : ${key}
Use the SAME API key on every device you want to sync.
If the subdomain is new, create it once in the DuckDNS dashboard
(label: ${SYNCYOMI_SUBDOMAIN%.duckdns.org}) so Caddy can issue TLS.
Acceptance test: on your phone with Wi-Fi OFF (cellular), configure the
sync above and confirm the library round-trips.
============================================================================
EOF
}
# --- status subcommand -------------------------------------------------------
status_cmd() {
print_setup_header "SyncYomi status"
echo
if [[ -f ${COMPOSE_FILE} ]]; then
docker compose -f "${COMPOSE_FILE}" ps
else
log_warn "No compose file at ${COMPOSE_FILE}"
fi
echo
local code
code="$(syncyomi_ready "${SYNCYOMI_LOCAL}" || true)"
if [[ ${code} == "204" || ${code} == "403" ]]; then
log_ok "Local API answering (${SYNCYOMI_LOCAL}, HTTP ${code})"
else
log_warn "Local API not answering (HTTP ${code:-none})"
fi
local sub="${SYNCYOMI_SUBDOMAIN:-kuhy-sync.duckdns.org}"
if [[ -f ${CONF_FILE} ]]; then
# shellcheck source=/dev/null
source "${CONF_FILE}"
sub="${SYNCYOMI_SUBDOMAIN}"
fi
if grep -qE "^${sub} \{" "${CADDYFILE}" 2>/dev/null; then
log_ok "Caddy block present for ${sub}"
else
log_warn "No Caddy block for ${sub}"
fi
if getent hosts "${sub}" >/dev/null 2>&1; then
log_ok "${sub} resolves"
else
log_warn "${sub} does not resolve"
fi
code="$(syncyomi_ready "https://${sub}" || true)"
if [[ ${code} == "204" || ${code} == "403" ]]; then
log_ok "External HTTPS reachable (https://${sub}, HTTP ${code})"
else
log_warn "External HTTPS not reachable yet (HTTP ${code:-none})"
fi
}
# --- main --------------------------------------------------------------------
setup_cmd() {
print_setup_header "Self-hosted SyncYomi manga sync"
preflight
load_config
write_compose
start_containers
wait_for_syncyomi
ensure_local_config
mint_api_key
configure_caddy
configure_duckdns
ensure_firewall
print_report
}

View File

@ -0,0 +1,142 @@
#!/bin/bash
# Compose file, container startup and readiness polling for SyncYomi.
#
# Sourced by setup_syncyomi.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# --- Step 3: docker-compose stack (host networking, loopback bind) -----------
write_compose() {
ensure_dir "${DATA_DIR}/config"
# network_mode: host + SyncYomi's host=127.0.0.1 keeps it loopback-only
# (reached by the host-networked Caddy) and dodges this host's default-drop
# nftables FORWARD chain that would kill a bridge-networked container.
umask 077
cat >"${COMPOSE_FILE}" <<EOF
# Generated by setup_syncyomi.sh — do not edit by hand.
services:
syncyomi:
container_name: syncyomi
image: ${SYNCYOMI_IMAGE}
restart: unless-stopped
network_mode: host
environment:
- TZ=${TZ_VALUE}
volumes:
- ./config:/config
EOF
log_ok "Wrote ${COMPOSE_FILE}"
}
start_containers() {
log_info "Starting SyncYomi container"
docker compose -f "${COMPOSE_FILE}" up -d
}
# Readiness probe. SyncYomi (v1.1.x) has no public /healthz, but GET
# /api/auth/onboard answers 204 (no user yet) or 403 (a user exists) once the
# API is serving — either means "up". Echoes the HTTP code; returns 0 if ready.
# Usage: syncyomi_ready "http://127.0.0.1:8282"
syncyomi_ready() {
local base="$1" code
code="$(curl -sS -o /dev/null -w '%{http_code}' "${base}/api/auth/onboard" 2>/dev/null || true)"
echo "${code}"
[[ ${code} == "204" || ${code} == "403" ]]
}
# --- Step 4: wait until the local API answers --------------------------------
wait_for_syncyomi() {
log_info "Waiting for SyncYomi to come up on ${SYNCYOMI_LOCAL}"
local i
for ((i = 0; i < 60; i++)); do
if syncyomi_ready "${SYNCYOMI_LOCAL}" >/dev/null; then
log_ok "SyncYomi is up (API answering)"
return 0
fi
sleep 2
done
die "SyncYomi did not become healthy in 120s — check 'docker logs syncyomi'."
}
# Defensive: SyncYomi generates config/config.toml on first run. Ensure it binds
# loopback-only (never 0.0.0.0, which would bypass Caddy/TLS) and serves at root.
ensure_local_config() {
[[ -f ${CONFIG_TOML} ]] || return 0
local changed=0
if grep -qE '^\s*host\s*=' "${CONFIG_TOML}"; then
if ! grep -qE '^\s*host\s*=\s*"127\.0\.0\.1"' "${CONFIG_TOML}"; then
sed -i -E 's|^\s*host\s*=.*|host = "127.0.0.1"|' "${CONFIG_TOML}"
changed=1
fi
fi
# Force an empty baseUrl (dedicated subdomain, not a sub-path).
if grep -qE '^\s*baseUrl\s*=' "${CONFIG_TOML}" &&
! grep -qE '^\s*baseUrl\s*=\s*""' "${CONFIG_TOML}"; then
sed -i -E 's|^\s*baseUrl\s*=.*|baseUrl = ""|' "${CONFIG_TOML}"
changed=1
fi
if [[ ${changed} -eq 1 ]]; then
log_info "Patched ${CONFIG_TOML} (host=127.0.0.1, baseUrl empty) — restarting"
docker compose -f "${COMPOSE_FILE}" restart
wait_for_syncyomi
fi
}
# --- Step 5: create first account + mint API key over the local REST API -----
mint_api_key() {
if [[ -f ${TOKEN_FILE} ]]; then
log_ok "API key already minted ($(<"${TOKEN_FILE}") stored in ${TOKEN_FILE})"
return 0
fi
log_info "Creating SyncYomi account and minting API key"
local jar body http key
jar="$(mktemp)"
# shellcheck disable=SC2064
trap "rm -f '${jar}'" RETURN
# JSON with proper escaping (password may contain +,/,= from base64).
body="$(jq -n --arg u "${SYNCYOMI_USER}" --arg p "${SYNCYOMI_PASSWORD}" \
'{username:$u,password:$p}')"
# Onboard the first user only if none exists yet (GET returns 204 when empty).
http="$(curl -fsS -o /dev/null -w '%{http_code}' "${SYNCYOMI_LOCAL}/api/auth/onboard" 2>/dev/null || true)"
if [[ ${http} == "204" ]]; then
http="$(curl -sS -o /dev/null -w '%{http_code}' \
-H 'Content-Type: application/json' -d "${body}" \
"${SYNCYOMI_LOCAL}/api/auth/onboard" 2>/dev/null || true)"
[[ ${http} =~ ^2 ]] || die "Onboard failed (HTTP ${http}) — check 'docker logs syncyomi'."
log_ok "Created first account '${SYNCYOMI_USER}'"
else
log_warn "An account already exists (onboard HTTP ${http}); trying stored credentials"
fi
# Log in to get a session cookie.
http="$(curl -sS -c "${jar}" -o /dev/null -w '%{http_code}' \
-H 'Content-Type: application/json' -d "${body}" \
"${SYNCYOMI_LOCAL}/api/auth/login" 2>/dev/null || true)"
if [[ ! ${http} =~ ^2 ]]; then
log_warn "Login failed (HTTP ${http}). A different account may already own this server."
log_warn "Create an API key manually at ${SYNCYOMI_LOCAL} → Settings → API Keys."
return 0
fi
# Reuse an existing 'tachiyomisy' key if one exists (idempotent); otherwise
# create one. scopes must be a non-empty array — SyncYomi rejects a null.
key="$(curl -sS -b "${jar}" "${SYNCYOMI_LOCAL}/api/keys" 2>/dev/null |
jq -r '[.[] | select(.name=="tachiyomisy")][0].key // empty')"
if [[ -n ${key} ]]; then
log_ok "Reusing existing 'tachiyomisy' API key"
else
key="$(curl -sS -b "${jar}" \
-H 'Content-Type: application/json' \
-d '{"name":"tachiyomisy","scopes":["read","write"]}' \
"${SYNCYOMI_LOCAL}/api/keys" 2>/dev/null | jq -r '.key // empty')"
[[ -n ${key} ]] || die "API key creation returned no key — check 'docker logs syncyomi'."
fi
umask 077
printf '%s\n' "${key}" >"${TOKEN_FILE}"
chmod 600 "${TOKEN_FILE}"
log_ok "Minted API key and stored it in ${TOKEN_FILE} (0600)"
}

View File

@ -0,0 +1,249 @@
#!/bin/bash
# Repo checkout, launcher install and MCP client registration.
#
# Sourced by install_unreal_mcp.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# ---------- Git clone/update ----------
setup_repo() {
mkdir -p "$INSTALL_ROOT"
if [[ ! -d "$REPO_DIR/.git" ]]; then
log "Cloning unreal-mcp into $REPO_DIR"
if require_cmd git; then
git clone "$REPO_URL" "$REPO_DIR"
else
fail "git is required but not found after install"
fi
else
log "Repo exists at $REPO_DIR"
if [[ $FORCE_UPDATE == true ]]; then
log "Updating repo with --force-update"
git -C "$REPO_DIR" fetch origin
git -C "$REPO_DIR" reset --hard origin/main
git -C "$REPO_DIR" pull --rebase --autostash
else
log "Pulling latest changes"
git -C "$REPO_DIR" pull --rebase --autostash
fi
fi
# Ensure ownership for the real user when script ran via sudo
if [[ $EUID -eq 0 ]]; then
chown -R "$ACTUAL_USER:$ACTUAL_USER" "$INSTALL_ROOT"
fi
}
# ---------- Launcher ----------
install_launcher() {
local bin_dir="$USER_HOME/.local/bin"
local python_dir="$REPO_DIR/Python"
local launcher="$bin_dir/unreal-mcp-server"
mkdir -p "$bin_dir"
cat > "$launcher" << EOF
#!/bin/bash
set -euo pipefail
exec uv --directory "$python_dir" run unreal_mcp_server.py "\${1:-}" < /dev/null
EOF
chmod +x "$launcher"
if [[ $EUID -eq 0 ]]; then chown "$ACTUAL_USER:$ACTUAL_USER" "$launcher"; fi
log "Installed launcher: $launcher"
}
# ---------- VS Code: Continue MCP config ----------
configure_continue() {
if [[ $CONFIGURE_CONTINUE != true ]]; then
log "Skipping Continue config (--no-continue)"
return 0
fi
local cont_dir="$USER_HOME/.continue"
local cont_cfg="$cont_dir/config.json"
local python_dir="$REPO_DIR/Python"
mkdir -p "$cont_dir"
# Base JSON when no config exists
local tmp_file
tmp_file="$(mktemp)"
if [[ ! -f $cont_cfg ]]; then
cat > "$tmp_file" << JSON
{
"mcpServers": {
"unrealMCP": {
"command": "uv",
"args": ["--directory", "$python_dir", "run", "unreal_mcp_server.py"]
}
}
}
JSON
mv "$tmp_file" "$cont_cfg"
else
# Merge using jq: ensure .mcpServers exists, then set/overwrite unrealMCP
if ! require_cmd jq; then
fail "jq is required to merge ~/.continue/config.json"
fi
jq --arg dir "$python_dir" '
.mcpServers = (.mcpServers // {}) |
.mcpServers.unrealMCP = {
command: "uv",
args: ["--directory", $dir, "run", "unreal_mcp_server.py"]
}
' "$cont_cfg" > "$tmp_file" && mv "$tmp_file" "$cont_cfg"
fi
if [[ $EUID -eq 0 ]]; then chown "$ACTUAL_USER:$ACTUAL_USER" "$cont_cfg"; fi
log "Configured Continue MCP at: $cont_cfg"
}
# ---------- VS Code user MCP (native) ----------
configure_vscode_user_mcp() {
if [[ $CONFIGURE_VSCODE_USER != true ]]; then
log "Skipping VS Code user MCP config (--no-vscode)"
return 0
fi
if ! require_cmd jq; then
fail "jq is required to compose VS Code --add-mcp JSON and to parse profiles"
fi
local python_dir="$REPO_DIR/Python"
local json
json=$(jq -n --arg dir "$python_dir" '{name:"unrealMCP", command:"uv", args:["--directory", $dir, "run", "unreal_mcp_server.py"]}')
# Handle multiple VS Code variants if present
local candidates=(code code-insiders codium)
local found_any=false
for cli in "${candidates[@]}"; do
if ! command -v "$cli" > /dev/null 2>&1; then
continue
fi
found_any=true
log "Registering MCP server in VS Code user profile via: $cli --add-mcp"
if "$cli" --add-mcp "$json" > "/tmp/${cli}-add-mcp.log" 2>&1; then
log "[$cli] user profile: unrealMCP added/updated"
else
sed -n '1,200p' "/tmp/${cli}-add-mcp.log" || true
fail "[$cli] --add-mcp failed for user profile. Ensure your VS Code supports MCP or rerun with --no-vscode."
fi
# Detect profiles with 'unreal' (case-insensitive) and add there too
local data_dir=""
case "$cli" in
code)
data_dir="$USER_HOME/.config/Code"
;;
code-insiders)
data_dir="$USER_HOME/.config/Code - Insiders"
;;
codium)
data_dir="$USER_HOME/.config/VSCodium"
;;
esac
local profiles_json="$data_dir/User/profiles/profiles.json"
if [[ -f $profiles_json ]]; then
# Extract profile names matching /unreal/i
mapfile -t unreal_profiles < <(jq -r '.profiles // [] | .[] | .name // empty | select(test("unreal"; "i"))' "$profiles_json")
if [[ ${#unreal_profiles[@]} -gt 0 ]]; then
log "[$cli] Found profiles with 'unreal': ${unreal_profiles[*]}"
local name
for name in "${unreal_profiles[@]}"; do
log "[$cli] Adding unrealMCP to profile: $name"
if "$cli" --profile "$name" --add-mcp "$json" > "/tmp/${cli}-add-mcp-${name// /_}.log" 2>&1; then
log "[$cli] profile '$name': unrealMCP added/updated"
else
sed -n '1,200p' "/tmp/${cli}-add-mcp-${name// /_}.log" || true
fail "[$cli] --add-mcp failed for profile '$name'."
fi
done
else
log "[$cli] No VS Code profiles with 'unreal' in name"
fi
else
log "[$cli] Profiles file not found: $profiles_json (skipping profile-specific adds)"
fi
done
if [[ $found_any == false ]]; then
fail "VS Code CLI not found (code/code-insiders/codium). Install VS Code and ensure 'code' CLI is available, or run with --no-vscode to skip."
fi
}
# ---------- Unreal Plugin copy (optional) ----------
install_plugin_into_project() {
[[ -n $PROJECT_UPROJECT ]] || return 0
local upath="$PROJECT_UPROJECT"
if [[ -d $upath ]]; then
# Resolve .uproject in the provided directory
mapfile -t _uprojects < <(find "$upath" -maxdepth 1 -type f -name "*.uproject" 2> /dev/null || true)
if [[ ${#_uprojects[@]} -eq 0 ]]; then
fail "--project directory '$upath' contains no .uproject files"
elif [[ ${#_uprojects[@]} -gt 1 ]]; then
printf '[ERROR] Multiple .uproject files found in %s:\n' "$upath" >&2
printf ' - %s\n' "${_uprojects[@]}" >&2
fail "Please pass the specific .uproject path to --project"
else
upath="${_uprojects[0]}"
log "Resolved .uproject: $upath"
fi
elif [[ -f $upath ]]; then
true
else
fail "--project path does not exist: $upath"
fi
if [[ ${upath##*.} != "uproject" ]]; then
fail "--project must point to a .uproject file (got: $upath)"
fi
local proj_dir
proj_dir="$(cd "$(dirname "$upath")" && pwd)"
RESOLVED_PROJECT_DIR="$proj_dir"
local src_plugin="$REPO_DIR/MCPGameProject/Plugins/UnrealMCP"
local dst_plugin="$proj_dir/Plugins/UnrealMCP"
if [[ ! -d $src_plugin ]]; then
fail "Source plugin not found at $src_plugin (did repo layout change?)"
fi
mkdir -p "$proj_dir/Plugins"
log "Copying UnrealMCP plugin to project: $dst_plugin"
rsync -a --delete "$src_plugin/" "$dst_plugin/"
# Set ownership back to actual user if run as root
if [[ $EUID -eq 0 ]]; then chown -R "$ACTUAL_USER:$ACTUAL_USER" "$proj_dir/Plugins"; fi
log "Plugin installed. Enable it from Unreal Editor (Edit > Plugins) if needed."
}
# ---------- Summary ----------
print_summary() {
local python_dir="$REPO_DIR/Python"
local plugin_dest="N/A"
if [[ -n $RESOLVED_PROJECT_DIR ]]; then
plugin_dest="$RESOLVED_PROJECT_DIR/Plugins/UnrealMCP"
fi
cat << EOF
============================================
Unreal MCP setup complete
============================================
Repo: $REPO_DIR
Python dir: $python_dir
Launcher: $USER_HOME/.local/bin/unreal-mcp-server
VS Code (Continue) MCP configured: ${CONFIGURE_CONTINUE}
- File: $USER_HOME/.continue/config.json
- Server ID: unrealMCP
VS Code (User profile) MCP configured: ${CONFIGURE_VSCODE_USER}
- Command used: code --add-mcp '{"name":"unrealMCP", "command":"uv", "args":["--directory","$python_dir","run","unreal_mcp_server.py"]}'
Optional usage:
- Run server manually: unreal-mcp-server
- In VS Code with Continue installed, the unrealMCP server will auto-start when needed.
Unreal plugin:
- Source: MCPGameProject/Plugins/UnrealMCP
- If you provided --project, the plugin was copied to: $plugin_dest
- In the Unreal Editor: Edit > Plugins > search "UnrealMCP" and enable. Restart when prompted.
Notes:
- Ensure you have Unreal Engine 5.5+ installed.
- The Python server listens to the Unreal plugin on TCP port 55557 by default.
- For other MCP clients (Claude Desktop, Cursor, Windsurf), copy the JSON snippet from the repo README to their config locations.
EOF
}

View File

@ -0,0 +1,213 @@
#!/bin/bash
# CV build, website generation and the Caddy stack snippets.
#
# Sourced by setup_personal_website.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# --- Phase 5: build the website --------------------------------------------
build_website() {
log_info "Installing website dependencies and building…"
(
cd "$WEBSITE_SRC" || die "Cannot enter ${WEBSITE_SRC}."
pnpm install --frozen-lockfile
pnpm run build
)
[[ -f "${WEBSITE_SRC}/dist/index.html" ]] ||
die "Build did not produce ${WEBSITE_SRC}/dist/index.html."
log_ok "Website built to ${WEBSITE_SRC}/dist."
}
# --- Phase 6: write the website's static-serve stack ------------------------
write_website_stack() {
ensure_dir "$WEBSITE_DATA_DIR"
cat >"$WEBSITE_COMPOSE" <<EOF
# Managed by setup_personal_website.sh — do not edit by hand.
services:
personal-website:
image: caddy:2.8
container_name: personal-website
restart: unless-stopped
network_mode: host
volumes:
- ${WEBSITE_SRC}/dist:/srv:ro
- ./Caddyfile:/etc/caddy/Caddyfile:ro
EOF
cat >"$WEBSITE_INNER_CADDY" <<EOF
# Managed by setup_personal_website.sh — do not edit by hand.
# Static file server on loopback; fronted by gitea-caddy on the public domain.
#
# admin off is REQUIRED: this container shares the host network namespace with
# gitea-caddy, so without it both Caddies would listen on the admin API (:2019)
# and a 'caddy reload' aimed at gitea-caddy could be applied to this one instead
# — which would make it grab 80/443 and run ACME. Disabling admin keeps this
# process strictly a loopback static server on ${WEBSITE_PORT}.
{
admin off
}
:${WEBSITE_PORT} {
root * /srv
try_files {path} /index.html
file_server
encode gzip
}
EOF
log_ok "Wrote ${WEBSITE_COMPOSE} and ${WEBSITE_INNER_CADDY}."
}
# --- Phase 7: front the website on the root domain --------------------------
write_website_snippet() {
cat >"$WEBSITE_SNIPPET" <<EOF
# Managed by setup_personal_website.sh — do not edit by hand.
${WEBSITE_DOMAIN} {
reverse_proxy 127.0.0.1:${WEBSITE_PORT}
}
EOF
log_ok "Wrote ${WEBSITE_SNIPPET}."
}
# --- Phase 8: start the website container -----------------------------------
wait_for_website() {
local _
for _ in $(seq 1 30); do
if curl -sf -o /dev/null "http://127.0.0.1:${WEBSITE_PORT}/"; then
return 0
fi
sleep 1
done
return 1
}
start_website() {
log_info "Starting the personal-website container…"
docker compose -f "$WEBSITE_COMPOSE" up -d
if wait_for_website; then
log_ok "Website answering on http://127.0.0.1:${WEBSITE_PORT}/."
else
die "Website did not become reachable on 127.0.0.1:${WEBSITE_PORT}."
fi
}
# --- Phase 9: reload the edge -----------------------------------------------
reload_caddy() {
if docker exec "$CADDY_CONTAINER" caddy validate --config /etc/caddy/Caddyfile >/dev/null 2>&1; then
docker exec "$CADDY_CONTAINER" caddy reload --config /etc/caddy/Caddyfile
log_ok "Reloaded ${CADDY_CONTAINER}."
else
die "Caddy config invalid — aborting reload. Check ${SITES_DIR}/*.caddy."
fi
}
# --- Phase 10: firewall -----------------------------------------------------
ensure_firewall() {
log_info "Ensuring ports 80/443 are open (idempotent)…"
sudo bash "$WG_SCRIPT" allow-web
}
# --- Phase 11: report -------------------------------------------------------
print_report() {
cat <<EOF
============================================================================
Personal website deployed.
============================================================================
Website : https://${WEBSITE_DOMAIN}/
Gitea : https://${GITEA_DOMAIN}/ (moved from the root)
Gitea moved to a subdomain. Re-point any local clones/mirrors:
git remote set-url <name> https://${GITEA_DOMAIN}/<owner>/<repo>.git
Acceptance test (do this on your phone):
Turn Wi-Fi OFF (use cellular) and open https://${WEBSITE_DOMAIN}/ —
it should load over HTTPS with the hero, live GitHub projects, and CV,
and be usable at phone width.
============================================================================
EOF
}
setup_cmd() {
print_setup_header "Personal website setup"
preflight
migrate_caddy_snippets
relocate_gitea
build_cv_json
build_website
write_website_stack
write_website_snippet
start_website
reload_caddy
ensure_firewall
print_report
log_ok "Personal website setup complete."
}
# --- status: self-diagnose --------------------------------------------------
status_line() {
if [[ $1 -eq 0 ]]; then
log_ok "$2"
else
log_warn "$2"
fi
}
check_http() {
# Prints 0 to stdout if the URL returns 200, else 1.
local url="$1" code
code="$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 "$url" 2>/dev/null || echo 000)"
[[ $code == "200" ]] && echo 0 || echo 1
}
status_cmd() {
print_setup_header "Personal website status"
if has_cmd node; then
status_line 0 "node present"
else
status_line 1 "node missing"
fi
if has_cmd pnpm; then
status_line 0 "pnpm present"
else
status_line 1 "pnpm missing"
fi
if [[ -f "${WEBSITE_SRC}/dist/index.html" ]]; then
status_line 0 "build present (dist/index.html)"
else
status_line 1 "build missing — run setup"
fi
if docker ps --format '{{.Names}}' | grep -qx personal-website; then
status_line 0 "personal-website container running"
else
status_line 1 "personal-website container not running"
fi
status_line "$(check_http "http://127.0.0.1:${WEBSITE_PORT}/")" \
"local static server (127.0.0.1:${WEBSITE_PORT})"
if [[ -f $WEBSITE_SNIPPET ]]; then
status_line 0 "Caddy website snippet present"
else
status_line 1 "Caddy website snippet missing"
fi
if grep -qE '^[[:space:]]*import[[:space:]]+/etc/caddy/sites' "$CADDYFILE" 2>/dev/null; then
status_line 0 "root Caddyfile uses snippet imports"
else
status_line 1 "root Caddyfile not migrated to imports"
fi
if getent hosts "$WEBSITE_DOMAIN" >/dev/null; then
status_line 0 "${WEBSITE_DOMAIN} resolves"
else
status_line 1 "${WEBSITE_DOMAIN} does not resolve"
fi
if getent hosts "$GITEA_DOMAIN" >/dev/null; then
status_line 0 "${GITEA_DOMAIN} resolves"
else
status_line 1 "${GITEA_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${WEBSITE_DOMAIN}/")" \
"external https://${WEBSITE_DOMAIN}/"
status_line "$(check_http "https://${GITEA_DOMAIN}/")" \
"external https://${GITEA_DOMAIN}/"
}

View File

@ -109,156 +109,9 @@ verify_prerequisites() {
fi
}
install_cert_sync() {
# Caddy renews on its own schedule; stunnel reads files from disk and must
# be told. A timer copies the current cert out of the container and
# reloads stunnel only when the content actually changed.
sudo install -d -m 700 "$CERT_DIR"
sudo tee "$SYNC_SCRIPT" >/dev/null <<EOF
#!/bin/bash
# Copy the Caddy-managed certificate for $DOMAIN out to stunnel.
# Generated by $SCRIPT_NAME - edit that instead.
set -euo pipefail
src="$(cert_source_dir)"
tmp="\$(mktemp -d)"
trap 'rm -rf "\$tmp"' EXIT
docker cp "$CADDY_CONTAINER:\$src/$DOMAIN.crt" "\$tmp/cert.pem"
docker cp "$CADDY_CONTAINER:\$src/$DOMAIN.key" "\$tmp/key.pem"
cat "\$tmp/cert.pem" "\$tmp/key.pem" >"\$tmp/combined.pem"
if ! cmp -s "\$tmp/combined.pem" "$CERT_DIR/combined.pem"; then
install -m 600 "\$tmp/combined.pem" "$CERT_DIR/combined.pem"
systemctl reload-or-restart stunnel-dot.service
echo "certificate updated for $DOMAIN"
fi
EOF
sudo chmod 755 "$SYNC_SCRIPT"
}
install_stunnel_conf() {
sudo tee "$STUNNEL_CONF" >/dev/null <<EOF
; DNS-over-TLS front end for the local dnsmasq blocklist.
; Generated by $SCRIPT_NAME - edit that instead.
foreground = yes
syslog = yes
[dns-over-tls]
accept = $BIND_ADDR:$DOT_PORT
connect = 127.0.0.1:53
cert = $CERT_DIR/combined.pem
; DoT is TLS 1.2+ only in practice; Android requires a publicly trusted cert.
sslVersionMin = TLSv1.2
EOF
}
install_units() {
sudo tee /etc/systemd/system/stunnel-dot.service >/dev/null <<EOF
[Unit]
Description=DNS-over-TLS front end for dnsmasq blocklist
After=network-online.target dnsmasq.service wg-quick@wg0.service
Wants=network-online.target
Requires=dnsmasq.service
; Binding to the WireGuard address fails if the interface is not up yet.
After=sys-devices-virtual-net-wg0.device
[Service]
ExecStart=/usr/bin/stunnel $STUNNEL_CONF
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
sudo tee /etc/systemd/system/dot-cert-sync.service >/dev/null <<EOF
[Unit]
Description=Copy the Caddy certificate for $DOMAIN to stunnel
[Service]
Type=oneshot
ExecStart=$SYNC_SCRIPT
EOF
sudo tee /etc/systemd/system/dot-cert-sync.timer >/dev/null <<EOF
[Unit]
Description=Daily certificate sync for the DoT resolver
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
}
open_firewall() {
# Binding to the WireGuard address is NOT sufficient on its own. The
# input chain has `policy drop` and admits only specific ports over wg0
# (ssh), so a DoT connection from the phone is dropped even though the
# tunnel itself is up and ICMP replies fine. That combination is
# confusing to debug -- ping works, the port does not -- so the rule is
# added explicitly, scoped to the tunnel interface.
if [[ "$BIND_ADDR" != "0.0.0.0" ]]; then
if command -v nft >/dev/null 2>&1 && sudo nft list table inet filter >/dev/null 2>&1; then
if sudo nft list table inet filter | grep -q "iifname \"wg0\" tcp dport $DOT_PORT"; then
log "nftables already permits $DOT_PORT on wg0"
else
sudo nft add rule inet filter input iifname wg0 tcp dport "$DOT_PORT" accept ||
log "WARNING: could not add nftables rule for $DOT_PORT on wg0"
log "Permitted TCP $DOT_PORT on wg0 only"
fi
fi
log "No router port-forward needed - $BIND_ADDR is WireGuard-only."
return
fi
if command -v nft >/dev/null 2>&1 && sudo nft list table inet filter >/dev/null 2>&1; then
if ! sudo nft list table inet filter | grep -q "dport $DOT_PORT"; then
# Rate limited, because a publicly bound DoT endpoint is an open
# resolver: TCP-only so not usable for classic UDP amplification,
# but still someone else's free DNS and a standing attack surface.
# A phone issues a handful of lookups a second at worst; 25/second
# with a burst of 50 is far above real use and far below abuse.
sudo nft add rule inet filter input tcp dport "$DOT_PORT" \
limit rate 25/second burst 50 packets accept ||
log "WARNING: could not add rate-limited nftables rule for $DOT_PORT"
log "Permitted TCP $DOT_PORT (rate limited 25/s, burst 50)"
fi
fi
log "Ensure your router forwards TCP $DOT_PORT to this host."
}
run_check() {
local ok=0
systemctl is-active --quiet stunnel-dot.service ||
{
log "FAIL stunnel-dot.service not active"
ok=1
}
ss -lnt 2>/dev/null | grep -qE ":$DOT_PORT\b" ||
{
log "FAIL nothing listening on $DOT_PORT"
ok=1
}
# $CERT_DIR is mode 700 and owned by root because it holds a private key,
# so an unprivileged [[ -s ]] reports "missing" for a file that is
# present. Test as root, or --check reports a false failure on a healthy
# install.
sudo test -s "$CERT_DIR/combined.pem" ||
{
log "FAIL certificate missing at $CERT_DIR/combined.pem"
ok=1
}
if command -v kdig >/dev/null 2>&1; then
kdig +tls "@$BIND_ADDR" -p "$DOT_PORT" +short example.com >/dev/null 2>&1 ||
{
log "FAIL DoT query did not answer"
ok=1
}
fi
[[ $ok -eq 0 ]] && log "OK - DoT resolver healthy on $DOMAIN:$DOT_PORT"
return "$ok"
}
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/dot_resolver_install.sh
source "$SCRIPT_DIR/lib/dot_resolver_install.sh"
main() {
if [[ $CHECK_ONLY -eq 1 ]]; then

View File

@ -126,220 +126,8 @@ fetch_dwm() {
log "dwm source now at commit $(git -C "$SRC_DIR" rev-parse --short HEAD) ($(git -C "$SRC_DIR" log -1 --format=%cd --date=short))"
}
# ---------------------------------------------------------------------------
# 3. Install our versioned config.h onto the fresh upstream clone. dwm.c stays
# pristine here — movestack()/togglefullscr() are defined inside config.h, so
# only the two intentional behaviour changes below patch dwm.c.
# ---------------------------------------------------------------------------
install_config() {
log "Installing config.h from the repo (${REPO_DWM_DIR}/config.h)…"
cp -- "${REPO_DWM_DIR}/config.h" "$SRC_DIR/config.h"
}
# ---------------------------------------------------------------------------
# 3b. Auto-merge bleeding-edge config churn. When upstream adds a new config
# knob (e.g. `refreshrate`), dwm.c starts referencing a symbol our
# hand-written config.h doesn't define, breaking the build. To keep
# "always latest master" sustainable, copy across any scalar knob that the
# current dwm.c needs but our config.h lacks, using upstream's default.
# Only single-line scalars referenced by dwm.c are merged (arrays we own
# and unused symbols are left alone), so our customisations always win.
# ---------------------------------------------------------------------------
heal_config() {
local defh="$SRC_DIR/config.def.h" cfgh="$SRC_DIR/config.h" dwmc="$SRC_DIR/dwm.c"
[[ -f "$defh" && -f "$dwmc" ]] || return 0
local line name added=0
while IFS= read -r line; do
name="$(sed -nE 's/^.*[^A-Za-z0-9_]([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=.*/\1/p' <<<"$line")"
[[ -n "$name" ]] || continue
grep -qw "$name" "$cfgh" && continue # we already define it — keep ours
grep -qw "$name" "$dwmc" || continue # dwm.c doesn't need it — skip
printf '%s\n' "$line" >>"$cfgh"
warn "config.h: auto-merged new upstream knob '$name' (bleeding-edge churn)"
added=1
done < <(grep -E '^[[:space:]]*static[[:space:]]+const[[:space:]]+[^={]*=[^;{]*;' "$defh")
((added)) && log "Merged upstream config symbol(s) into config.h for this build."
return 0
}
# ---------------------------------------------------------------------------
# 3c. Focus-on-click: stop the pointer from changing focus / switching monitors.
# dwm defaults to focus-follows-mouse — and worse, crossing the screen
# boundary over EMPTY space (motionnotify) switches the active monitor, which
# yanks focus away from a fullscreen game on the other screen (no window edge
# to stop the pointer). We rewrite enternotify + motionnotify to no-ops so
# focus only changes on a CLICK or via the Mod+,/. (Mod+Ctrl+arrows) keys.
# Applied as an idempotent source rewrite after each reset so it survives the
# bleeding-edge `git pull`. perl -0777 slurps the file so the multi-line
# function bodies match at once (.*? stops at the first column-0 `}`, i.e. the
# function's own closing brace — nested if-block braces are tab-indented).
# The dwm/patches/focus-on-click.patch file is the human-readable equivalent.
# If upstream refactors these handlers the rewrite no-ops and we warn loudly
# rather than silently dropping the behaviour.
# ---------------------------------------------------------------------------
apply_focusonclick() {
local src="$SRC_DIR/dwm.c"
[[ -f "$src" ]] || return 0
perl -0777 -i -pe '
s!\nenternotify\(XEvent \*e\)\n\{.*?\n\}\n!\nenternotify(XEvent *e)\n{\n\t/* focusonclick: pointer never changes focus; use a click or Mod+keys. */\n\t(void)e;\n}\n!s;
s!\nmotionnotify\(XEvent \*e\)\n\{.*?\n\}\n!\nmotionnotify(XEvent *e)\n{\n\t/* focusonclick: keep the active monitor fixed when crossing screens. */\n\t(void)e;\n}\n!s;
' "$src"
# Verify both rewrites landed; warn (never abort) if upstream changed shape.
local ok=1
grep -q 'focusonclick: pointer never changes focus' "$src" || ok=0
grep -q 'focusonclick: keep the active monitor fixed' "$src" || ok=0
if ((ok)); then
log "Applied focus-on-click (pointer no longer changes focus or switches monitors)."
else
warn "focus-on-click rewrite did NOT match upstream dwm.c — pointer focus unchanged."
warn "enternotify/motionnotify were likely refactored upstream; update dwm/patches."
fi
return 0
}
# ---------------------------------------------------------------------------
# 3d. Auto pointer-confinement on fullscreen. dwm has no pointer barriers, so on
# a dual-monitor setup the cursor slides off a fullscreen game onto the other
# screen (there is no window edge to stop it). We hook setfullscreen() to
# start the `pointer-confine` helper (XFixes barriers) when a window goes
# fullscreen and stop it when fullscreen ends; unmanage() also stops it so a
# game that closes WHILE fullscreen can never leave the cursor trapped. The
# hook is a quick `if (system(...)) {}` — the `if` consumes system()'s result
# so -Wall stays warning-free; the trailing `&` returns to dwm immediately.
# Reapplied after each reset (idempotent via git) and self-verifying; the
# dwm/patches/fullscreen-pointer-confine.patch file mirrors it for reading.
# ---------------------------------------------------------------------------
apply_fullscreen_confine_hook() {
local src="$SRC_DIR/dwm.c"
[[ -f "$src" ]] || return 0
perl -0777 -i -pe '
s!(\n\t\tc->isfullscreen = 1;\n)!$1\t\tif (system("pconfine-auto on &")) {}\n!;
s!(\n\t\tc->isfullscreen = 0;\n)!$1\t\tif (system("pconfine-auto off &")) {}\n!;
s!(\nunmanage\(Client \*c, int destroyed\)\n\{\n\tMonitor \*m = c->mon;\n\tXWindowChanges wc;\n)!$1\tif (c->isfullscreen) { if (system("pconfine-auto off &")) {} }\n!;
' "$src"
# Expect: 1 "on", 2 "off" (setfullscreen-leave + unmanage). Warn if not.
local on off
on=$(grep -c 'pconfine-auto on' "$src")
off=$(grep -c 'pconfine-auto off' "$src")
if [[ "$on" == 1 && "$off" == 2 ]]; then
log "Applied auto pointer-confinement hook (locks the cursor to a fullscreen window's screen)."
else
warn "pointer-confine hook only partially applied (on=$on off=$off, expected 1/2)."
warn "setfullscreen/unmanage were likely refactored upstream; update dwm/patches."
fi
return 0
}
# ---------------------------------------------------------------------------
# 4. Build & install (PREFIX defaults to /usr/local).
# ---------------------------------------------------------------------------
build_install() {
log "Compiling dwm…"
make -C "$SRC_DIR" clean >/dev/null
make -C "$SRC_DIR" 2>&1 | tail -15
log "Installing dwm (sudo make install)…"
sudo make -C "$SRC_DIR" install 2>&1 | tail -8
}
# ---------------------------------------------------------------------------
# 4b. Build & install the pointer-confine helper (XFixes barriers) from the
# versioned dwm/pointer-confine.c. Standalone C so it stays out of dwm.c;
# dwm only spawns it via the setfullscreen() hook. If the X dev headers are
# missing it fails soft: warn and skip, leaving the rest of dwm fully working
# (fullscreen just won't auto-lock the cursor).
# ---------------------------------------------------------------------------
build_pointer_confine() {
log "Compiling pointer-confine from the repo (${REPO_DWM_DIR}/pointer-confine.c)…"
local bin
bin="$(mktemp)"
if cc -std=c99 -pedantic -Wall -O2 "${REPO_DWM_DIR}/pointer-confine.c" -o "$bin" \
-lX11 -lXfixes -lXinerama 2>/tmp/pointer-confine-build.log; then
sudo install -m 755 "$bin" "$BIN_CONFINE"
log "Installed $BIN_CONFINE."
else
warn "pointer-confine failed to compile — fullscreen cursor-lock disabled (dwm itself is fine):"
sed 's/^/ /' /tmp/pointer-confine-build.log >&2 || true
fi
rm -f "$bin"
}
# ---------------------------------------------------------------------------
# 5. Install the helper scripts (from the repo) and register the lightdm
# xsession. The scripts are the versioned files in dwm/bin/; we just place
# them on PATH with the right mode.
# ---------------------------------------------------------------------------
write_session_files() {
log "Installing helper scripts from the repo and the lightdm xsession entry…"
sudo install -m 755 "${REPO_DWM_DIR}/bin/dwm-session" "$BIN_SESSION"
sudo install -m 755 "${REPO_DWM_DIR}/bin/dwmstatus" "$BIN_STATUS"
sudo install -m 755 "${REPO_DWM_DIR}/bin/dwm-rebuild" "$BIN_REBUILD"
sudo install -m 755 "${REPO_DWM_DIR}/bin/switch-wm" "$BIN_SWITCH"
sudo install -m 755 "${REPO_DWM_DIR}/bin/pconfine-auto" "$BIN_CONFINE_AUTO"
# --- xsession entry for lightdm (absolute Exec path) --------------------
sudo tee "$XSESSION" >/dev/null <<'DESKTOP_EOF'
[Desktop Entry]
Name=dwm (i3-like)
Comment=dynamic window manager, compiled from source
Exec=/usr/local/bin/dwm-session
TryExec=/usr/local/bin/dwm
Type=Application
DesktopNames=dwm
DESKTOP_EOF
}
# ---------------------------------------------------------------------------
# 6. Verify the build links and the session is registered.
# ---------------------------------------------------------------------------
verify() {
log "Verifying install…"
local ver
ver="$(dwm -v 2>&1)" || true # dwm -v prints version then exit(1)
log "dwm version: ${ver:-<none>}"
command -v dwm >/dev/null && log "dwm binary: $(command -v dwm)"
[[ -f "$XSESSION" ]] && log "xsession registered: $XSESSION"
}
print_summary() {
cat <<SUMMARY
dwm is installed alongside i3 (i3 untouched).
This machine autologins (no session picker), so choose the WM you boot into:
switch-wm dwm -> boot dwm switch-wm i3 -> boot i3 switch-wm -> show
then reboot. Recovery if dwm misbehaves: TTY (Ctrl+Alt+F3) -> 'switch-wm i3' -> reboot.
Key bindings (Mod = Super):
Mod+Return terminator Mod+d dmenu
Mod+j / Mod+k focus next / prev Mod+Shift+j/k move in stack
Mod+h / Mod+l shrink / grow master Mod+i/Shift+i +/- master count
Mod+1..0 view tag 1..10 Mod+Shift+1..0 send to tag
Mod+f fullscreen Mod+Shift+space toggle floating
Mod+t / Mod+w tiling / monocle Mod+Shift+Return promote to master
Mod+Shift+q kill window Mod+Shift+e exit dwm
Mod+m mic mute Mod+Shift+r recompile (dwm-rebuild)
Two monitors (no i3-style per-output workspaces — see config.h note):
Mod+, / Mod+. focus the other screen (or Mod+Ctrl+Left/Right)
Mod+Shift+, / Mod+Shift+. throw window there (or Mod+Ctrl+Shift+L/R)
Focus-on-click is ON: the pointer no longer steals focus or switches monitors
when it crosses screens. Focus changes on click/keys.
Fullscreen cursor-lock is ON: when a window goes fullscreen (games), the cursor
is trapped on that screen (XFixes barriers) and released when fullscreen ends.
Stuck barrier? Mod+Shift+p force-releases it.
Status bar (clock, temps, load, RAM, volume) needs xsetroot:
sudo pacman -S xorg-xsetroot # then log out / back in
Preview it now without the bar: dwmstatus once
Customise (permanent): edit files in linux_configuration/dwm/ then re-run this
script. Quick experiment: edit ~/.local/src/dwm/config.h + run 'dwm-rebuild'
(re-running setup_dwm.sh overwrites it from the repo).
SUMMARY
}
# shellcheck source=lib/dwm_config.sh
source "$SCRIPT_DIR/lib/dwm_config.sh"
main() {
validate_repo_files

View File

@ -163,66 +163,9 @@ mint_api_token() {
log_ok "API token saved to ${ADMIN_TOKEN_FILE} (chmod 600)."
}
open_firewall() {
if [[ -x $WIREGUARD_SCRIPT ]]; then
sudo "$WIREGUARD_SCRIPT" allow-web
else
log_warn "Could not find ${WIREGUARD_SCRIPT} -- open tcp/80 and tcp/443 manually."
fi
}
attempt_upnp() {
has_cmd upnpc || {
log_warn "upnpc not installed -- skipping automatic port-forward attempt."
return 0
}
local lan_ip
lan_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')
[[ -n $lan_ip ]] || {
log_warn "Could not detect LAN IP -- skipping UPnP."
return 0
}
if upnpc -e "gitea-https" -a "$lan_ip" 443 443 tcp >/dev/null 2>&1 &&
upnpc -e "gitea-http" -a "$lan_ip" 80 80 tcp >/dev/null 2>&1; then
log_ok "UPnP port mapping succeeded for 80 and 443 -> ${lan_ip}."
else
log_warn "UPnP port mapping failed or unsupported by your router."
fi
}
print_router_instructions() {
local lan_ip
lan_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')
cat <<EOF
=== Manual step: verify port forwarding on your router (cannot be automated) ===
1. Log into your router admin page (often http://192.168.1.1).
2. Find "Port Forwarding" / "Virtual Server" / "NAT" settings.
3. Forward TCP 80 -> ${lan_ip}:80 and TCP 443 -> ${lan_ip}:443.
4. Save (and reboot the router if it requires it).
5. Confirm from OUTSIDE your LAN (e.g. phone on cellular data):
https://${GITEA_DOMAIN}
EOF
}
status_cmd() {
echo "=== Containers ==="
docker compose -f "$COMPOSE_FILE" ps 2>/dev/null || echo "(not deployed)"
echo
echo "=== Caddy certificate ==="
docker logs gitea-caddy 2>&1 | grep -i "certificate obtained" | tail -3 || echo "(no certificate log entry yet)"
}
usage() {
cat <<EOF
Usage: $0 <command>
Commands:
setup Full first-time setup (idempotent, safe to re-run).
status Show container and certificate status.
help Show this message.
EOF
}
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/gitea_network.sh
source "$SCRIPT_DIR/lib/gitea_network.sh"
main() {
local cmd="${1:-help}"

View File

@ -141,216 +141,9 @@ start_ollama() {
wait_for_url "http://localhost:${OLLAMA_PORT}/api/tags" "Ollama API" 30
}
# ── 4. Create Modelfile with developer system prompt ─────────────────────────
create_modelfile() {
section "Creating custom model with developer system prompt"
# shellcheck source=lib/local_llm_model.sh
source "$SCRIPT_DIR/lib/local_llm_model.sh"
# Condense Claude preferences into a system prompt (~1 K tokens).
# Note: hooks, skills, and Claude Code MCP tools do NOT port to local models.
# This only captures code-style, persona, and workflow preferences.
local modelfile
modelfile="$(mktemp --suffix=.modelfile)"
cat > "$modelfile" << MODELFILE_EOF
FROM ${MODEL}
PARAMETER num_ctx ${CTX_LEN}
PARAMETER temperature 0.6
PARAMETER top_p 0.95
PARAMETER top_k 20
SYSTEM """
You are a coding assistant for Krzysztof (kuhy) Rudnicki, a software developer
who maintains personal automation and app monorepos.
## About me
- Stack: Python, Bash, C/C++, TypeScript, Dart/Flutter, Go
- OS: Arch Linux, i3 window manager
- Key repos: testsAndMisc (automation), linux-configuration, praca_magisterska
## Code style
Python:
- Use from __future__ import annotations for forward refs
- Google docstring convention (triple-quoted, brief summary + Args/Returns)
- Absolute imports only, no relative imports
- Type hints required on every function signature
- Prefer typed dataclasses over plain dicts
Shell (bash):
- Always set -euo pipefail at the top
- Double-quote all variable expansions
- Avoid fork-heavy patterns: prefer /proc, /sys, bash builtins over \$(...)
in tight loops or status-bar scripts (fork-storm anti-pattern)
- Use jq/yq for JSON/YAML, not grep/awk
- NEVER embed multi-line Python logic inside shell heredocs — put it in a
separate .py file and invoke with python3 path/to/file.py
TypeScript:
- Target ES2022, pure ESM (no CommonJS require)
- No any — use unknown + narrowing
- Discriminated unions for state machines
- async/await + structured error handling
## Behaviour I expect
- Keep responses brief and direct — no filler preamble
- Ask before making high-impact changes (schema changes, deleting data)
- If you spot a bad approach, say so before complying
- Development order: implement → run to verify → confirm → tests
(tests are always LAST, not first)
- Include only one short comment per non-obvious block; no inline summaries
of what the code obviously does
## Testing rules
- 100% branch coverage required for Python packages
- Use pytest + coverage; never mock the filesystem in integration tests
- Shell scripts: shellcheck must pass with no suppressions
## Git workflow
- Commit directly to main (no branches for personal repo)
- Conventional commit format: type: brief description
- Always run pre-commit hooks before committing
"""
MODELFILE_EOF
local custom_model="${MODEL/:/-}-dev"
ollama create "$custom_model" -f "$modelfile"
rm -f "$modelfile"
ok "Custom model created: $custom_model (includes developer system prompt)"
ok "Load '$custom_model' in Open WebUI for kuhy-personalised responses"
}
# ── 5. Pull base model ────────────────────────────────────────────────────────
pull_model() {
section "Pulling ${MODEL}"
# Check if already present
if curl -sf "http://localhost:${OLLAMA_PORT}/api/tags" \
| grep -q "\"${MODEL}\""; then
ok "${MODEL} already downloaded"
return
fi
warn "Downloading ${MODEL} — approx 20 GB. This will take a while."
warn "Progress is shown live; do not interrupt."
ollama pull "${MODEL}"
ok "${MODEL} downloaded"
}
# ── 6. Set up Open WebUI via Docker ───────────────────────────────────────────
setup_webui() {
section "Setting up Open WebUI"
# Remove existing container so we can apply any config changes cleanly
if docker ps -a --format '{{.Names}}' | grep -qx "$WEBUI_CONTAINER"; then
warn "Removing existing $WEBUI_CONTAINER container..."
docker rm -f "$WEBUI_CONTAINER"
fi
docker pull ghcr.io/open-webui/open-webui:main
docker run -d \
--name "$WEBUI_CONTAINER" \
--restart always \
-p "${WEBUI_PORT}:8080" \
-v "${WEBUI_VOLUME}:/app/backend/data" \
-e OLLAMA_BASE_URL="http://host.docker.internal:${OLLAMA_PORT}" \
--add-host=host.docker.internal:host-gateway \
ghcr.io/open-webui/open-webui:main
ok "Open WebUI container started on port ${WEBUI_PORT}"
}
# ── 7. Enable Docker on boot ──────────────────────────────────────────────────
enable_autostart() {
section "Enabling auto-start on boot"
# Docker daemon must start for the container (restart=always) to come up
sudo systemctl enable docker
ok "docker.service enabled on boot"
ok "Ollama is already enabled; Open WebUI container uses restart=always"
}
# ── 8. Verify: GPU utilisation + generation speed ─────────────────────────────
verify_gpu() {
section "Verifying GPU utilisation and generation speed"
# Warm up with a short generation and measure tok/s
warn "Running a warm-up generation (checking GPU offload + speed)..."
local start_ts end_ts elapsed toks_per_sec
start_ts="$(date +%s%N)"
local response
response="$(curl -sf "http://localhost:${OLLAMA_PORT}/api/generate" \
-d "{\"model\":\"${MODEL}\",\"prompt\":\"Reply with exactly: ready\",\"stream\":false}" \
--max-time 120)"
end_ts="$(date +%s%N)"
elapsed=$(( (end_ts - start_ts) / 1000000 )) # milliseconds
if [[ -z "$response" ]]; then
err "No response from Ollama — generation failed"
return 1
fi
# Parse eval_count (output tokens) and eval_duration (nanoseconds) from response
local eval_count eval_duration_ns
eval_count="$(printf '%s' "$response" | grep -o '"eval_count":[0-9]*' | grep -o '[0-9]*' || echo 0)"
eval_duration_ns="$(printf '%s' "$response" | grep -o '"eval_duration":[0-9]*' | grep -o '[0-9]*' || echo 1)"
if (( eval_count > 0 && eval_duration_ns > 0 )); then
toks_per_sec=$(( eval_count * 1000000000 / eval_duration_ns ))
ok "Generation speed: ${toks_per_sec} tok/s (${eval_count} tokens in ${elapsed}ms)"
if (( toks_per_sec < 10 )); then
warn "Speed is below 10 tok/s — model may be partially CPU-offloaded"
warn "Run: ollama ps to check GPU layer count"
warn "If GPU% < 100, try reducing CTX_LEN in this script or use a smaller quant"
fi
else
warn "Could not parse tok/s from response; check manually with: ollama ps"
fi
# Check GPU offload via ollama ps
warn "Checking GPU layer utilisation..."
if command -v ollama &>/dev/null; then
ollama ps 2>/dev/null | head -10 || true
fi
ok "Verify done — see ollama ps output above for GPU% column"
}
# ── 9. WebUI readiness check ──────────────────────────────────────────────────
verify_webui() {
section "Waiting for Open WebUI to become ready"
wait_for_url "http://localhost:${WEBUI_PORT}" "Open WebUI" 60
}
# ── Summary ───────────────────────────────────────────────────────────────────
print_summary() {
local custom_model="${MODEL/:/-}-dev"
printf '\n\033[1;32m'
printf '═══════════════════════════════════════════════════════\n'
printf ' Local LLM setup complete!\n'
printf '═══════════════════════════════════════════════════════\n'
printf ' Open WebUI: http://localhost:%s\n' "$WEBUI_PORT"
printf ' Ollama API: http://localhost:%s\n' "$OLLAMA_PORT"
printf ' Primary model: %s (%d K context)\n' "$MODEL" $(( CTX_LEN / 1024 ))
printf ' Dev model: %s (with code-style system prompt)\n' "$custom_model"
printf '\n'
printf ' GPU fit notes:\n'
printf ' Current context: %d K (safe for 24 GB VRAM)\n' $(( CTX_LEN / 1024 ))
printf ' To try 24 K: edit CTX_LEN=24576 in this script\n'
printf ' To try 32 K: edit CTX_LEN=32768 (risks partial CPU offload)\n'
printf ' After changes: re-run this script; check tok/s in verify step\n'
printf '\n'
printf ' To use with Claude Code:\n'
printf ' Claude Code uses the Anthropic API — it cannot point at Ollama\n'
printf ' directly (different wire format). Use Open WebUI for local-model\n'
printf ' coding sessions, or ask about setting up a LiteLLM proxy.\n'
printf '═══════════════════════════════════════════════════════\n'
printf '\033[0m\n'
}
# ── Main ──────────────────────────────────────────────────────────────────────
main() {
log "Local LLM setup — model: ${MODEL}, GPU: RTX 3090, VRAM: 24 GB"

View File

@ -167,212 +167,8 @@ build_cv_json() {
fi
}
# --- Phase 5: build the website --------------------------------------------
build_website() {
log_info "Installing website dependencies and building…"
(
cd "$WEBSITE_SRC"
pnpm install --frozen-lockfile
pnpm run build
)
[[ -f "${WEBSITE_SRC}/dist/index.html" ]] ||
die "Build did not produce ${WEBSITE_SRC}/dist/index.html."
log_ok "Website built to ${WEBSITE_SRC}/dist."
}
# --- Phase 6: write the website's static-serve stack ------------------------
write_website_stack() {
ensure_dir "$WEBSITE_DATA_DIR"
cat >"$WEBSITE_COMPOSE" <<EOF
# Managed by setup_personal_website.sh — do not edit by hand.
services:
personal-website:
image: caddy:2.8
container_name: personal-website
restart: unless-stopped
network_mode: host
volumes:
- ${WEBSITE_SRC}/dist:/srv:ro
- ./Caddyfile:/etc/caddy/Caddyfile:ro
EOF
cat >"$WEBSITE_INNER_CADDY" <<EOF
# Managed by setup_personal_website.sh — do not edit by hand.
# Static file server on loopback; fronted by gitea-caddy on the public domain.
#
# admin off is REQUIRED: this container shares the host network namespace with
# gitea-caddy, so without it both Caddies would listen on the admin API (:2019)
# and a 'caddy reload' aimed at gitea-caddy could be applied to this one instead
# — which would make it grab 80/443 and run ACME. Disabling admin keeps this
# process strictly a loopback static server on ${WEBSITE_PORT}.
{
admin off
}
:${WEBSITE_PORT} {
root * /srv
try_files {path} /index.html
file_server
encode gzip
}
EOF
log_ok "Wrote ${WEBSITE_COMPOSE} and ${WEBSITE_INNER_CADDY}."
}
# --- Phase 7: front the website on the root domain --------------------------
write_website_snippet() {
cat >"$WEBSITE_SNIPPET" <<EOF
# Managed by setup_personal_website.sh — do not edit by hand.
${WEBSITE_DOMAIN} {
reverse_proxy 127.0.0.1:${WEBSITE_PORT}
}
EOF
log_ok "Wrote ${WEBSITE_SNIPPET}."
}
# --- Phase 8: start the website container -----------------------------------
wait_for_website() {
local _
for _ in $(seq 1 30); do
if curl -sf -o /dev/null "http://127.0.0.1:${WEBSITE_PORT}/"; then
return 0
fi
sleep 1
done
return 1
}
start_website() {
log_info "Starting the personal-website container…"
docker compose -f "$WEBSITE_COMPOSE" up -d
if wait_for_website; then
log_ok "Website answering on http://127.0.0.1:${WEBSITE_PORT}/."
else
die "Website did not become reachable on 127.0.0.1:${WEBSITE_PORT}."
fi
}
# --- Phase 9: reload the edge -----------------------------------------------
reload_caddy() {
if docker exec "$CADDY_CONTAINER" caddy validate --config /etc/caddy/Caddyfile >/dev/null 2>&1; then
docker exec "$CADDY_CONTAINER" caddy reload --config /etc/caddy/Caddyfile
log_ok "Reloaded ${CADDY_CONTAINER}."
else
die "Caddy config invalid — aborting reload. Check ${SITES_DIR}/*.caddy."
fi
}
# --- Phase 10: firewall -----------------------------------------------------
ensure_firewall() {
log_info "Ensuring ports 80/443 are open (idempotent)…"
sudo bash "$WG_SCRIPT" allow-web
}
# --- Phase 11: report -------------------------------------------------------
print_report() {
cat <<EOF
============================================================================
Personal website deployed.
============================================================================
Website : https://${WEBSITE_DOMAIN}/
Gitea : https://${GITEA_DOMAIN}/ (moved from the root)
Gitea moved to a subdomain. Re-point any local clones/mirrors:
git remote set-url <name> https://${GITEA_DOMAIN}/<owner>/<repo>.git
Acceptance test (do this on your phone):
Turn Wi-Fi OFF (use cellular) and open https://${WEBSITE_DOMAIN}/ —
it should load over HTTPS with the hero, live GitHub projects, and CV,
and be usable at phone width.
============================================================================
EOF
}
setup_cmd() {
print_setup_header "Personal website setup"
preflight
migrate_caddy_snippets
relocate_gitea
build_cv_json
build_website
write_website_stack
write_website_snippet
start_website
reload_caddy
ensure_firewall
print_report
log_ok "Personal website setup complete."
}
# --- status: self-diagnose --------------------------------------------------
status_line() {
if [[ $1 -eq 0 ]]; then
log_ok "$2"
else
log_warn "$2"
fi
}
check_http() {
# Prints 0 to stdout if the URL returns 200, else 1.
local url="$1" code
code="$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 "$url" 2>/dev/null || echo 000)"
[[ $code == "200" ]] && echo 0 || echo 1
}
status_cmd() {
print_setup_header "Personal website status"
if has_cmd node; then
status_line 0 "node present"
else
status_line 1 "node missing"
fi
if has_cmd pnpm; then
status_line 0 "pnpm present"
else
status_line 1 "pnpm missing"
fi
if [[ -f "${WEBSITE_SRC}/dist/index.html" ]]; then
status_line 0 "build present (dist/index.html)"
else
status_line 1 "build missing — run setup"
fi
if docker ps --format '{{.Names}}' | grep -qx personal-website; then
status_line 0 "personal-website container running"
else
status_line 1 "personal-website container not running"
fi
status_line "$(check_http "http://127.0.0.1:${WEBSITE_PORT}/")" \
"local static server (127.0.0.1:${WEBSITE_PORT})"
if [[ -f $WEBSITE_SNIPPET ]]; then
status_line 0 "Caddy website snippet present"
else
status_line 1 "Caddy website snippet missing"
fi
if grep -qE '^[[:space:]]*import[[:space:]]+/etc/caddy/sites' "$CADDYFILE" 2>/dev/null; then
status_line 0 "root Caddyfile uses snippet imports"
else
status_line 1 "root Caddyfile not migrated to imports"
fi
if getent hosts "$WEBSITE_DOMAIN" >/dev/null; then
status_line 0 "${WEBSITE_DOMAIN} resolves"
else
status_line 1 "${WEBSITE_DOMAIN} does not resolve"
fi
if getent hosts "$GITEA_DOMAIN" >/dev/null; then
status_line 0 "${GITEA_DOMAIN} resolves"
else
status_line 1 "${GITEA_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${WEBSITE_DOMAIN}/")" \
"external https://${WEBSITE_DOMAIN}/"
status_line "$(check_http "https://${GITEA_DOMAIN}/")" \
"external https://${GITEA_DOMAIN}/"
}
# shellcheck source=lib/website_build.sh
source "$SCRIPT_DIR/lib/website_build.sh"
main() {
local cmd="${1:-setup}"

View File

@ -122,278 +122,10 @@ save_config() {
log_ok "Saved config to ${CONF_FILE} (0600)"
}
# --- Step 3: docker-compose stack (host networking, loopback bind) -----------
write_compose() {
ensure_dir "${DATA_DIR}/config"
# network_mode: host + SyncYomi's host=127.0.0.1 keeps it loopback-only
# (reached by the host-networked Caddy) and dodges this host's default-drop
# nftables FORWARD chain that would kill a bridge-networked container.
umask 077
cat >"${COMPOSE_FILE}" <<EOF
# Generated by setup_syncyomi.sh — do not edit by hand.
services:
syncyomi:
container_name: syncyomi
image: ${SYNCYOMI_IMAGE}
restart: unless-stopped
network_mode: host
environment:
- TZ=${TZ_VALUE}
volumes:
- ./config:/config
EOF
log_ok "Wrote ${COMPOSE_FILE}"
}
start_containers() {
log_info "Starting SyncYomi container"
docker compose -f "${COMPOSE_FILE}" up -d
}
# Readiness probe. SyncYomi (v1.1.x) has no public /healthz, but GET
# /api/auth/onboard answers 204 (no user yet) or 403 (a user exists) once the
# API is serving — either means "up". Echoes the HTTP code; returns 0 if ready.
# Usage: syncyomi_ready "http://127.0.0.1:8282"
syncyomi_ready() {
local base="$1" code
code="$(curl -sS -o /dev/null -w '%{http_code}' "${base}/api/auth/onboard" 2>/dev/null || true)"
echo "${code}"
[[ ${code} == "204" || ${code} == "403" ]]
}
# --- Step 4: wait until the local API answers --------------------------------
wait_for_syncyomi() {
log_info "Waiting for SyncYomi to come up on ${SYNCYOMI_LOCAL}"
local i
for ((i = 0; i < 60; i++)); do
if syncyomi_ready "${SYNCYOMI_LOCAL}" >/dev/null; then
log_ok "SyncYomi is up (API answering)"
return 0
fi
sleep 2
done
die "SyncYomi did not become healthy in 120s — check 'docker logs syncyomi'."
}
# Defensive: SyncYomi generates config/config.toml on first run. Ensure it binds
# loopback-only (never 0.0.0.0, which would bypass Caddy/TLS) and serves at root.
ensure_local_config() {
[[ -f ${CONFIG_TOML} ]] || return 0
local changed=0
if grep -qE '^\s*host\s*=' "${CONFIG_TOML}"; then
if ! grep -qE '^\s*host\s*=\s*"127\.0\.0\.1"' "${CONFIG_TOML}"; then
sed -i -E 's|^\s*host\s*=.*|host = "127.0.0.1"|' "${CONFIG_TOML}"
changed=1
fi
fi
# Force an empty baseUrl (dedicated subdomain, not a sub-path).
if grep -qE '^\s*baseUrl\s*=' "${CONFIG_TOML}" &&
! grep -qE '^\s*baseUrl\s*=\s*""' "${CONFIG_TOML}"; then
sed -i -E 's|^\s*baseUrl\s*=.*|baseUrl = ""|' "${CONFIG_TOML}"
changed=1
fi
if [[ ${changed} -eq 1 ]]; then
log_info "Patched ${CONFIG_TOML} (host=127.0.0.1, baseUrl empty) — restarting"
docker compose -f "${COMPOSE_FILE}" restart
wait_for_syncyomi
fi
}
# --- Step 5: create first account + mint API key over the local REST API -----
mint_api_key() {
if [[ -f ${TOKEN_FILE} ]]; then
log_ok "API key already minted ($(<"${TOKEN_FILE}") stored in ${TOKEN_FILE})"
return 0
fi
log_info "Creating SyncYomi account and minting API key"
local jar body http key
jar="$(mktemp)"
# shellcheck disable=SC2064
trap "rm -f '${jar}'" RETURN
# JSON with proper escaping (password may contain +,/,= from base64).
body="$(jq -n --arg u "${SYNCYOMI_USER}" --arg p "${SYNCYOMI_PASSWORD}" \
'{username:$u,password:$p}')"
# Onboard the first user only if none exists yet (GET returns 204 when empty).
http="$(curl -fsS -o /dev/null -w '%{http_code}' "${SYNCYOMI_LOCAL}/api/auth/onboard" 2>/dev/null || true)"
if [[ ${http} == "204" ]]; then
http="$(curl -sS -o /dev/null -w '%{http_code}' \
-H 'Content-Type: application/json' -d "${body}" \
"${SYNCYOMI_LOCAL}/api/auth/onboard" 2>/dev/null || true)"
[[ ${http} =~ ^2 ]] || die "Onboard failed (HTTP ${http}) — check 'docker logs syncyomi'."
log_ok "Created first account '${SYNCYOMI_USER}'"
else
log_warn "An account already exists (onboard HTTP ${http}); trying stored credentials"
fi
# Log in to get a session cookie.
http="$(curl -sS -c "${jar}" -o /dev/null -w '%{http_code}' \
-H 'Content-Type: application/json' -d "${body}" \
"${SYNCYOMI_LOCAL}/api/auth/login" 2>/dev/null || true)"
if [[ ! ${http} =~ ^2 ]]; then
log_warn "Login failed (HTTP ${http}). A different account may already own this server."
log_warn "Create an API key manually at ${SYNCYOMI_LOCAL} → Settings → API Keys."
return 0
fi
# Reuse an existing 'tachiyomisy' key if one exists (idempotent); otherwise
# create one. scopes must be a non-empty array — SyncYomi rejects a null.
key="$(curl -sS -b "${jar}" "${SYNCYOMI_LOCAL}/api/keys" 2>/dev/null |
jq -r '[.[] | select(.name=="tachiyomisy")][0].key // empty')"
if [[ -n ${key} ]]; then
log_ok "Reusing existing 'tachiyomisy' API key"
else
key="$(curl -sS -b "${jar}" \
-H 'Content-Type: application/json' \
-d '{"name":"tachiyomisy","scopes":["read","write"]}' \
"${SYNCYOMI_LOCAL}/api/keys" 2>/dev/null | jq -r '.key // empty')"
[[ -n ${key} ]] || die "API key creation returned no key — check 'docker logs syncyomi'."
fi
umask 077
printf '%s\n' "${key}" >"${TOKEN_FILE}"
chmod 600 "${TOKEN_FILE}"
log_ok "Minted API key and stored it in ${TOKEN_FILE} (0600)"
}
# --- Step 6: Caddy reverse-proxy block (append + reload) ---------------------
configure_caddy() {
if grep -qE "^${SYNCYOMI_SUBDOMAIN} \{" "${CADDYFILE}"; then
log_ok "Caddyfile already has a block for ${SYNCYOMI_SUBDOMAIN}"
else
log_info "Adding Caddy block for ${SYNCYOMI_SUBDOMAIN}"
# NOTE: appended to the shared Gitea Caddyfile. Re-running setup_gitea.sh
# regenerates that file and drops this block — re-run setup_syncyomi.sh
# to restore it. Caddyfile uses tab indentation.
printf '\n%s {\n\treverse_proxy 127.0.0.1:%s\n}\n' "${SYNCYOMI_SUBDOMAIN}" "${SYNCYOMI_PORT}" \
>>"${CADDYFILE}"
fi
docker exec "${CADDY_CONTAINER}" caddy reload --config "${CADDYFILE_IN_CONTAINER}" ||
die "caddy reload failed — check 'docker logs ${CADDY_CONTAINER}'."
log_ok "Caddy reloaded (auto-HTTPS will be issued once the subdomain resolves)"
}
# --- Step 7: DuckDNS subdomain (extend existing updater; no new cron) --------
configure_duckdns() {
local label="${SYNCYOMI_SUBDOMAIN%.duckdns.org}"
if grep -qE "domains=[^&\"']*${label}([,&\"']|$)" "${DUCKDNS_UPDATER}"; then
log_ok "DuckDNS updater already includes '${label}'"
else
log_info "Adding '${label}' to the existing DuckDNS updater"
sed -i -E "s|(domains=)([^&\"']*)|\1\2,${label}|" "${DUCKDNS_UPDATER}"
fi
# Refresh now (harmless if the subdomain isn't registered yet).
bash "${DUCKDNS_UPDATER}" >/dev/null 2>&1 || log_warn "DuckDNS update returned non-zero (register the subdomain first)."
if getent hosts "${SYNCYOMI_SUBDOMAIN}" >/dev/null 2>&1; then
log_ok "${SYNCYOMI_SUBDOMAIN} resolves"
else
log_warn "${SYNCYOMI_SUBDOMAIN} does not resolve yet — create the '${label}' subdomain in the DuckDNS dashboard."
fi
}
# --- Step 8: firewall (open 80/443 via the owning script, idempotent) -------
ensure_firewall() {
if sudo nft list ruleset 2>/dev/null | grep -qE 'dport \{[^}]*80[^}]*443'; then
log_ok "Firewall already allows tcp/80 + tcp/443"
elif [[ -f ${WG_SCRIPT} ]]; then
log_info "Opening 80/443 via setup_wireguard_ssh.sh allow-web"
sudo bash "${WG_SCRIPT}" allow-web
else
log_warn "setup_wireguard_ssh.sh not found — ensure tcp/80+443 are open."
fi
}
# --- Step 9: report ----------------------------------------------------------
print_report() {
local url="https://${SYNCYOMI_SUBDOMAIN}"
local key="(create one in the web UI)"
[[ -f ${TOKEN_FILE} ]] && key="$(<"${TOKEN_FILE}")"
cat <<EOF
============================================================================
SyncYomi is up.
Host address : ${url}
API key : ${key}
Web UI login : ${SYNCYOMI_USER} / (password in ${CONF_FILE})
TachiyomiSY setup (on the phone):
Settings → Data & storage → Sync → SyncYomi
Host : ${url}
API key : ${key}
Use the SAME API key on every device you want to sync.
If the subdomain is new, create it once in the DuckDNS dashboard
(label: ${SYNCYOMI_SUBDOMAIN%.duckdns.org}) so Caddy can issue TLS.
Acceptance test: on your phone with Wi-Fi OFF (cellular), configure the
sync above and confirm the library round-trips.
============================================================================
EOF
}
# --- status subcommand -------------------------------------------------------
status_cmd() {
print_setup_header "SyncYomi status"
echo
if [[ -f ${COMPOSE_FILE} ]]; then
docker compose -f "${COMPOSE_FILE}" ps
else
log_warn "No compose file at ${COMPOSE_FILE}"
fi
echo
local code
code="$(syncyomi_ready "${SYNCYOMI_LOCAL}" || true)"
if [[ ${code} == "204" || ${code} == "403" ]]; then
log_ok "Local API answering (${SYNCYOMI_LOCAL}, HTTP ${code})"
else
log_warn "Local API not answering (HTTP ${code:-none})"
fi
local sub="${SYNCYOMI_SUBDOMAIN:-kuhy-sync.duckdns.org}"
if [[ -f ${CONF_FILE} ]]; then
# shellcheck source=/dev/null
source "${CONF_FILE}"
sub="${SYNCYOMI_SUBDOMAIN}"
fi
if grep -qE "^${sub} \{" "${CADDYFILE}" 2>/dev/null; then
log_ok "Caddy block present for ${sub}"
else
log_warn "No Caddy block for ${sub}"
fi
if getent hosts "${sub}" >/dev/null 2>&1; then
log_ok "${sub} resolves"
else
log_warn "${sub} does not resolve"
fi
code="$(syncyomi_ready "https://${sub}" || true)"
if [[ ${code} == "204" || ${code} == "403" ]]; then
log_ok "External HTTPS reachable (https://${sub}, HTTP ${code})"
else
log_warn "External HTTPS not reachable yet (HTTP ${code:-none})"
fi
}
# --- main --------------------------------------------------------------------
setup_cmd() {
print_setup_header "Self-hosted SyncYomi manga sync"
preflight
load_config
write_compose
start_containers
wait_for_syncyomi
ensure_local_config
mint_api_key
configure_caddy
configure_duckdns
ensure_firewall
print_report
}
# shellcheck source=lib/syncyomi_stack.sh
source "$SCRIPT_DIR/lib/syncyomi_stack.sh"
# shellcheck source=lib/syncyomi_expose.sh
source "$SCRIPT_DIR/lib/syncyomi_expose.sh"
main() {
local cmd="${1:-setup}"

View File

@ -97,262 +97,10 @@ install_optional_tools() {
pacman -S --needed --noconfirm "${packages[@]}"
}
collect_basics() {
run_and_log "Kernel" uname -a
run_and_log "Uptime" uptime
run_and_log "Memory" free -h
run_and_log "Swap" swapon --show
run_and_log "CPU (lscpu)" lscpu
run_and_log "Disk Usage" df -h /
run_and_log "Boot Time" systemd-analyze
run_and_log "Failed Units" systemctl --failed --no-pager
run_and_log "Recent Errors (this boot)" journalctl -b -p err --no-pager -n 200
local cpu_count
cpu_count=$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
local load1
load1=$(awk '{print int($1)}' /proc/loadavg 2>/dev/null || echo 0)
if [[ ${load1:-0} -ge ${cpu_count:-1} ]]; then
add_finding "1-minute load average is at/above CPU thread count (${load1}/${cpu_count}); background tasks may be saturating the system."
fi
local failed_count
failed_count=$(systemctl --failed --no-legend 2>/dev/null | wc -l || true)
failed_count=${failed_count//[[:space:]]/}
if [[ ${failed_count:-0} -gt 0 ]]; then
add_finding "One or more systemd units are failed (${failed_count}); failed services can cause repeated retries and instability."
fi
local acpi_error_count
acpi_error_count=$(journalctl -b -p err --no-pager 2>/dev/null | grep -ic 'acpi' || true)
if [[ ${acpi_error_count:-0} -ge 5 ]]; then
add_finding "Frequent ACPI errors detected in current boot (${acpi_error_count}); BIOS/firmware update may improve stability."
fi
local top_snapshot
top_snapshot=$(ps -eo pid,comm,%cpu,%mem --sort=-%cpu | head -n 12 || true)
{
echo
echo "=== Top CPU Processes ==="
echo "$top_snapshot"
} >>"$REPORT_FILE"
local xorg_cpu
xorg_cpu=$(ps -C Xorg -o %cpu= | awk '{sum+=$1} END {printf "%.0f", sum+0}' || echo 0)
if [[ ${xorg_cpu:-0} -ge 20 ]]; then
add_finding "Xorg is using high CPU (${xorg_cpu}%); desktop/compositor/GPU driver path may be a primary slowdown source."
fi
}
check_cpu_governor() {
# An ARRAY, not a newline-joined string: the awk/grep calls below need one
# argument per file. With the old unquoted "$gov_files" an empty result
# also left awk with NO file operands, so it fell through to reading stdin
# and the diagnostic hung instead of reporting 'not found'.
local -a gov_files=()
mapfile -t gov_files < <(find /sys/devices/system/cpu -maxdepth 3 -name scaling_governor 2>/dev/null || true)
if ((${#gov_files[@]} == 0)); then
add_action "CPU governor files not found (may be unsupported on this platform)."
return
fi
local summary
summary=$(awk '{count[$1]++} END {for (g in count) printf "%s:%d ", g, count[g]}' "${gov_files[@]}" 2>/dev/null || true)
echo "CPU governor summary: ${summary:-unknown}" >>"$REPORT_FILE"
if grep -q '^powersave$' "${gov_files[@]}" 2>/dev/null; then
add_finding "CPU governor includes 'powersave' on one or more cores; this can make high-end hardware feel slow."
fi
}
check_thermal_state() {
if has_cmd sensors; then
run_and_log "Temperatures (sensors)" sensors
else
add_action "Install lm_sensors and run 'sensors' to verify thermal throttling."
fi
if has_cmd dmesg; then
local therm_hits
therm_hits=$(dmesg | grep -Ei 'throttl|thermal|overheat|cpu clock throttled' | tail -n 30 || true)
if [[ -n $therm_hits ]]; then
add_finding "Kernel logs show thermal/throttling related messages."
{
echo
echo "=== Thermal/Throttling dmesg excerpts ==="
echo "$therm_hits"
} >>"$REPORT_FILE"
fi
fi
}
check_power_services() {
local tlp_enabled="false"
local ppd_enabled="false"
if systemctl is-enabled tlp.service >/dev/null 2>&1; then
tlp_enabled="true"
fi
if systemctl is-enabled power-profiles-daemon.service >/dev/null 2>&1; then
ppd_enabled="true"
fi
echo "Power services: tlp=${tlp_enabled}, power-profiles-daemon=${ppd_enabled}" >>"$REPORT_FILE"
if [[ $tlp_enabled == "true" && $ppd_enabled == "true" ]]; then
add_finding "Both TLP and power-profiles-daemon are enabled; they often conflict and cause inconsistent performance."
fi
if [[ $tlp_enabled == "false" && $ppd_enabled == "false" ]]; then
add_action "No power management daemon is enabled; consider installing/enabling power-profiles-daemon for predictable AC/battery behavior."
fi
}
check_storage_health() {
run_and_log "Block Devices" lsblk -o NAME,MODEL,ROTA,SIZE,TYPE,MOUNTPOINT,FSTYPE
if has_cmd fstrim; then
run_and_log "fstrim dry-run" fstrim -av --dry-run
fi
if systemctl is-enabled fstrim.timer >/dev/null 2>&1; then
add_action "fstrim.timer is enabled (good for SSD performance longevity)."
else
add_finding "fstrim.timer is not enabled; SSD maintenance trimming may be missing."
fi
if has_cmd smartctl; then
local root_disk
root_disk=$(findmnt -n -o SOURCE / | sed 's/[0-9]*$//' | sed 's/p$//' || true)
if [[ -n ${root_disk:-} && -b $root_disk ]]; then
run_and_log "SMART Summary ($root_disk)" smartctl -H "$root_disk"
fi
else
add_action "Install smartmontools and run SMART health checks for your SSD/NVMe."
fi
}
check_memory_pressure() {
local mem_total mem_available swap_total swap_free
mem_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
mem_available=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
swap_total=$(awk '/SwapTotal/ {print $2}' /proc/meminfo)
swap_free=$(awk '/SwapFree/ {print $2}' /proc/meminfo)
if [[ ${swap_total:-0} -gt 0 ]]; then
local swap_used
swap_used=$((swap_total - swap_free))
local swap_pct
swap_pct=$((swap_used * 100 / swap_total))
echo "Swap usage: ${swap_pct}%" >>"$REPORT_FILE"
if [[ $swap_pct -ge 35 && ${mem_available:-0} -gt $((mem_total / 3)) ]]; then
add_finding "High swap usage while RAM is still available; this can cause stutter."
add_action "Consider lowering swappiness (temporary: sudo sysctl vm.swappiness=10)."
fi
fi
if [[ -f /proc/pressure/memory ]]; then
run_and_log "Memory PSI" cat /proc/pressure/memory
fi
}
check_gpu_state() {
if has_cmd nvidia-smi; then
run_and_log "NVIDIA State" nvidia-smi
local pstate util power
pstate=$(nvidia-smi --query-gpu=pstate --format=csv,noheader 2>/dev/null | head -n 1 | xargs || true)
util=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 | xargs || true)
power=$(nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits 2>/dev/null | head -n 1 | xargs || true)
{
echo "NVIDIA pstate: ${pstate:-unknown}"
echo "NVIDIA util: ${util:-unknown}%"
echo "NVIDIA power: ${power:-unknown}W"
} >>"$REPORT_FILE"
if [[ ${pstate:-} == "P0" && ${util:-100} -le 5 ]]; then
add_finding "NVIDIA GPU is in P0 high-performance state while mostly idle; this can increase heat and trigger thermal limits."
add_action "If laptop has hybrid graphics, prefer iGPU mode for desktop workloads and use dGPU on demand."
fi
else
run_and_log "PCI VGA Devices" lspci -nnk | grep -A3 -Ei 'vga|3d|display'
fi
}
check_journal_size() {
local journal_line
journal_line=$(journalctl --disk-usage 2>/dev/null || true)
echo "Journal usage: ${journal_line:-unknown}" >>"$REPORT_FILE"
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ (G|M) ]]; then
local value unit
value="${BASH_REMATCH[1]}"
unit="${BASH_REMATCH[2]}"
if [[ $unit == "G" ]]; then
add_finding "Systemd journal is large (${value}G); excessive logs can waste I/O and disk space."
fi
fi
}
apply_safe_fixes() {
if [[ $APPLY_SAFE_FIXES != "true" ]]; then
return
fi
log_info "Applying safe fixes..."
if ! systemctl is-enabled fstrim.timer >/dev/null 2>&1; then
systemctl enable --now fstrim.timer
add_action "Enabled and started fstrim.timer."
fi
if systemctl is-enabled tlp.service >/dev/null 2>&1 && systemctl is-enabled power-profiles-daemon.service >/dev/null 2>&1; then
systemctl disable --now tlp.service
add_action "Disabled tlp.service to avoid conflict with power-profiles-daemon."
fi
local journal_line
journal_line=$(journalctl --disk-usage 2>/dev/null || true)
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
journalctl --vacuum-size=300M
add_action "Vacuumed systemd journal to 300M."
fi
}
print_summary() {
echo
echo "=============================="
echo " Arch Performance Diagnostics"
echo "=============================="
echo "Report: $REPORT_FILE"
echo
if [[ ${#FINDINGS[@]} -eq 0 ]]; then
log_ok "No high-confidence bottlenecks detected by automated checks."
else
log_warn "Likely issues found (${#FINDINGS[@]}):"
local item
for item in "${FINDINGS[@]}"; do
echo " - $item"
done
fi
if [[ ${#ACTIONS[@]} -gt 0 ]]; then
echo
log_info "Actions/recommendations:"
local action
for action in "${ACTIONS[@]}"; do
echo " - $action"
done
fi
echo
echo "Recommended next command for deep per-process analysis:"
echo " sudo iotop -oPa"
echo " top"
echo " systemd-analyze blame"
}
# shellcheck source=lib/arch_perf_probes.sh
source "$SCRIPT_DIR/lib/arch_perf_probes.sh"
# shellcheck source=lib/arch_perf_report.sh
source "$SCRIPT_DIR/lib/arch_perf_report.sh"
main() {
parse_args "$@"

View File

@ -166,120 +166,9 @@ fix_power_management() {
return 0
}
# ===================================================================
# Fix 3: Journal vacuum + permanent size cap
# ===================================================================
fix_journal() {
local usage_line
usage_line=$(journalctl --disk-usage 2>/dev/null || true)
# shellcheck source=lib/arch_perf_fixes.sh
source "$SCRIPT_DIR/lib/arch_perf_fixes.sh"
local needs_vacuum=false
if [[ $usage_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
needs_vacuum=true
fi
if [[ $needs_vacuum == "true" ]]; then
journalctl --vacuum-size=300M
else
log_ok "Journal is already under 1GiB."
fi
# Create permanent size cap via drop-in
local dropin_dir="/etc/systemd/journald.conf.d"
local dropin_file="$dropin_dir/size-limit.conf"
if [[ -f $dropin_file ]] && grep -q 'SystemMaxUse=300M' "$dropin_file"; then
log_ok "Journal size cap already configured."
else
mkdir -p "$dropin_dir"
cat >"$dropin_file" <<'JOURNALEOF'
[Journal]
SystemMaxUse=300M
JOURNALEOF
systemctl restart systemd-journald
fi
return 0
}
# ===================================================================
# Fix 4: Disable NetworkManager-wait-online
# ===================================================================
fix_nm_wait_online() {
if ! systemctl is-enabled NetworkManager-wait-online.service >/dev/null 2>&1; then
log_ok "NetworkManager-wait-online is already disabled — skipping."
return 0
fi
systemctl disable NetworkManager-wait-online.service
return 0
}
# ===================================================================
# Fix 5: media-organizer.service
# ===================================================================
fix_media_organizer() {
local service_file="/etc/systemd/system/media-organizer.service"
# Find the organize_downloads.sh script
local script_path=""
local candidates=(
"/home/kuhy/testsAndMisc/linux_configuration/scripts/utils/organize_downloads.sh"
"/home/kuhy/linux-configuration/scripts/utils/organize_downloads.sh"
)
for candidate in "${candidates[@]}"; do
if [[ -f $candidate ]]; then
script_path="$candidate"
break
fi
done
if [[ -z $script_path ]]; then
log_warn "organize_downloads.sh not found — skipping media-organizer fix."
return 0
fi
local target_user="${SUDO_USER:-kuhy}"
# Check if already correct
if [[ -f $service_file ]]; then
if grep -q "User=$target_user" "$service_file" &&
grep -q "ExecStart=$script_path" "$service_file"; then
log_ok "media-organizer.service is already correctly configured — skipping."
return 0
fi
fi
systemctl stop media-organizer.service 2>/dev/null || true
cat >"$service_file" <<EOF
[Unit]
Description=Media File Organizer
After=graphical-session.target
Wants=graphical-session.target
[Service]
Type=oneshot
User=$target_user
Group=$target_user
ExecStart=$script_path
StandardOutput=journal
StandardError=journal
RemainAfterExit=no
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl reset-failed media-organizer.service 2>/dev/null || true
systemctl enable media-organizer.service
return 0
}
# ===================================================================
# Apply all fixes
# ===================================================================
main() {
apply_fix \
"Fix 1/5: Enable NVIDIA hardware acceleration (RenderAccel → true)" \

View File

@ -158,178 +158,9 @@ remove_if_exists() {
return 1
}
# Fix 1: Handle corrupted Local State file (most common crash cause)
fix_local_state() {
log_info "Checking Local State file..."
local local_state="$THORIUM_CONFIG_DIR/Local State"
# shellcheck source=lib/thorium_repairs.sh
source "$SCRIPT_DIR/lib/thorium_repairs.sh"
if [[ -f $local_state ]]; then
# Check if it's valid JSON
if ! python3 -c "import json; json.load(open('$local_state'))" 2> /dev/null; then
log_warn "Local State file appears corrupted"
backup_if_exists "$local_state"
else
# Even if valid JSON, back it up as it can still cause crashes
log_info "Local State exists - backing up (common crash source)"
backup_if_exists "$local_state"
fi
else
log_info "No Local State file found (OK for fresh install)"
fi
}
# Fix 2: Clear singleton lock files
fix_singleton_locks() {
log_info "Clearing singleton lock files..."
local locks=(
"$THORIUM_CONFIG_DIR/SingletonLock"
"$THORIUM_CONFIG_DIR/SingletonSocket"
"$THORIUM_CONFIG_DIR/SingletonCookie"
)
local cleared=0
for lock in "${locks[@]}"; do
if remove_if_exists "$lock"; then
((cleared++)) || true
fi
done
if [[ $cleared -eq 0 ]]; then
log_info "No stale lock files found"
fi
}
# Fix 3: Clear GPU cache
fix_gpu_cache() {
log_info "Clearing GPU cache..."
local gpu_paths=(
"$THORIUM_CONFIG_DIR/GPUCache"
"$THORIUM_CONFIG_DIR/Default/GPUCache"
"$THORIUM_CONFIG_DIR/ShaderCache"
"$THORIUM_CONFIG_DIR/Default/ShaderCache"
)
local cleared=0
for cache in "${gpu_paths[@]}"; do
if remove_if_exists "$cache"; then
((cleared++)) || true
fi
done
if [[ $cleared -eq 0 ]]; then
log_info "No GPU cache to clear"
fi
}
# Fix 4: Clear crash reports (can accumulate and cause issues)
fix_crash_reports() {
log_info "Clearing old crash reports..."
local crash_dir="$THORIUM_CONFIG_DIR/Crash Reports"
if [[ -d $crash_dir ]]; then
local crash_count
crash_count=$(find "$crash_dir" -type f 2> /dev/null | wc -l)
if [[ $crash_count -gt 0 ]]; then
if [[ $DRY_RUN == true ]]; then
echo " [dry-run] Would clear $crash_count crash report(s)"
else
rm -rf "$crash_dir"
log_ok "Cleared $crash_count crash report(s)"
fi
fi
fi
}
# Fix 5: Aggressive cleaning (optional)
fix_aggressive() {
if [[ $AGGRESSIVE != true ]]; then
return
fi
log_warn "Applying aggressive fixes (may lose some site data)..."
local aggressive_paths=(
"$THORIUM_CONFIG_DIR/Default/Service Worker"
"$THORIUM_CONFIG_DIR/Default/Cache"
"$THORIUM_CONFIG_DIR/Default/Code Cache"
"$THORIUM_CONFIG_DIR/Default/IndexedDB"
"$THORIUM_CONFIG_DIR/BrowserMetrics"
"$THORIUM_CONFIG_DIR/component_crx_cache"
)
for path in "${aggressive_paths[@]}"; do
remove_if_exists "$path"
done
# Backup potentially corrupted databases
local db_files=(
"$THORIUM_CONFIG_DIR/Default/Web Data"
"$THORIUM_CONFIG_DIR/Default/History"
)
for db in "${db_files[@]}"; do
if [[ -f $db ]]; then
log_info "Checking database: $(basename "$db")"
# Simple corruption check - if sqlite3 can't open it, back it up
if command -v sqlite3 &> /dev/null; then
if ! sqlite3 "$db" "PRAGMA integrity_check;" &> /dev/null; then
log_warn "Database may be corrupted: $(basename "$db")"
backup_if_exists "$db"
fi
fi
fi
done
}
# Test if Thorium starts successfully
test_thorium() {
if [[ $TEST_AFTER != true ]]; then
return
fi
log_info "Testing Thorium startup..."
if [[ $DRY_RUN == true ]]; then
echo " [dry-run] Would test thorium-browser startup"
return
fi
# Start Thorium in background
thorium-browser &> /dev/null &
local pid=$!
# Wait a few seconds and check if it's still running
sleep 4
if kill -0 "$pid" 2> /dev/null; then
log_ok "Thorium started successfully! (PID: $pid)"
echo -e "${GREEN}Fix successful!${NC} Thorium is now running."
# Offer to keep it running or kill it
read -r -p "Keep browser running? [Y/n] " response
case "$response" in
[nN]*)
kill "$pid" 2> /dev/null || true
log_info "Browser closed"
;;
*)
log_info "Browser left running"
;;
esac
else
log_error "Thorium still crashing after fixes"
echo -e "${RED}Standard fixes did not resolve the issue.${NC}"
echo ""
echo "Try these additional steps:"
echo " 1. Run with --aggressive flag for deeper cleaning"
echo " 2. Test with fresh profile: thorium-browser --user-data-dir=/tmp/thorium-test"
echo " 3. Reinstall: yay -S thorium-browser-bin"
echo " 4. Check NVIDIA drivers: nvidia-smi"
exit 1
fi
}
# Main execution
main() {
echo "========================================"
echo " Thorium Browser Fix Script"

View File

@ -0,0 +1,121 @@
#!/bin/bash
# Journal, NetworkManager and media-organizer performance fixes.
#
# Sourced by fix_arch_performance.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# ===================================================================
# Fix 3: Journal vacuum + permanent size cap
# ===================================================================
fix_journal() {
local usage_line
usage_line=$(journalctl --disk-usage 2>/dev/null || true)
local needs_vacuum=false
if [[ $usage_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
needs_vacuum=true
fi
if [[ $needs_vacuum == "true" ]]; then
journalctl --vacuum-size=300M
else
log_ok "Journal is already under 1GiB."
fi
# Create permanent size cap via drop-in
local dropin_dir="/etc/systemd/journald.conf.d"
local dropin_file="$dropin_dir/size-limit.conf"
if [[ -f $dropin_file ]] && grep -q 'SystemMaxUse=300M' "$dropin_file"; then
log_ok "Journal size cap already configured."
else
mkdir -p "$dropin_dir"
cat >"$dropin_file" <<'JOURNALEOF'
[Journal]
SystemMaxUse=300M
JOURNALEOF
systemctl restart systemd-journald
fi
return 0
}
# ===================================================================
# Fix 4: Disable NetworkManager-wait-online
# ===================================================================
fix_nm_wait_online() {
if ! systemctl is-enabled NetworkManager-wait-online.service >/dev/null 2>&1; then
log_ok "NetworkManager-wait-online is already disabled — skipping."
return 0
fi
systemctl disable NetworkManager-wait-online.service
return 0
}
# ===================================================================
# Fix 5: media-organizer.service
# ===================================================================
fix_media_organizer() {
local service_file="/etc/systemd/system/media-organizer.service"
# Find the organize_downloads.sh script
local script_path=""
local candidates=(
"/home/kuhy/testsAndMisc/linux_configuration/scripts/utils/organize_downloads.sh"
"/home/kuhy/linux-configuration/scripts/utils/organize_downloads.sh"
)
for candidate in "${candidates[@]}"; do
if [[ -f $candidate ]]; then
script_path="$candidate"
break
fi
done
if [[ -z $script_path ]]; then
log_warn "organize_downloads.sh not found — skipping media-organizer fix."
return 0
fi
local target_user="${SUDO_USER:-kuhy}"
# Check if already correct
if [[ -f $service_file ]]; then
if grep -q "User=$target_user" "$service_file" &&
grep -q "ExecStart=$script_path" "$service_file"; then
log_ok "media-organizer.service is already correctly configured — skipping."
return 0
fi
fi
systemctl stop media-organizer.service 2>/dev/null || true
cat >"$service_file" <<EOF
[Unit]
Description=Media File Organizer
After=graphical-session.target
Wants=graphical-session.target
[Service]
Type=oneshot
User=$target_user
Group=$target_user
ExecStart=$script_path
StandardOutput=journal
StandardError=journal
RemainAfterExit=no
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl reset-failed media-organizer.service 2>/dev/null || true
systemctl enable media-organizer.service
return 0
}
# ===================================================================
# Apply all fixes
# ===================================================================

View File

@ -0,0 +1,166 @@
#!/bin/bash
# Individual diagnostic probes for the Arch performance report.
#
# Sourced by diagnose_arch_performance.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
collect_basics() {
run_and_log "Kernel" uname -a
run_and_log "Uptime" uptime
run_and_log "Memory" free -h
run_and_log "Swap" swapon --show
run_and_log "CPU (lscpu)" lscpu
run_and_log "Disk Usage" df -h /
run_and_log "Boot Time" systemd-analyze
run_and_log "Failed Units" systemctl --failed --no-pager
run_and_log "Recent Errors (this boot)" journalctl -b -p err --no-pager -n 200
local cpu_count
cpu_count=$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
local load1
load1=$(awk '{print int($1)}' /proc/loadavg 2>/dev/null || echo 0)
if [[ ${load1:-0} -ge ${cpu_count:-1} ]]; then
add_finding "1-minute load average is at/above CPU thread count (${load1}/${cpu_count}); background tasks may be saturating the system."
fi
local failed_count
failed_count=$(systemctl --failed --no-legend 2>/dev/null | wc -l || true)
failed_count=${failed_count//[[:space:]]/}
if [[ ${failed_count:-0} -gt 0 ]]; then
add_finding "One or more systemd units are failed (${failed_count}); failed services can cause repeated retries and instability."
fi
local acpi_error_count
acpi_error_count=$(journalctl -b -p err --no-pager 2>/dev/null | grep -ic 'acpi' || true)
if [[ ${acpi_error_count:-0} -ge 5 ]]; then
add_finding "Frequent ACPI errors detected in current boot (${acpi_error_count}); BIOS/firmware update may improve stability."
fi
local top_snapshot
top_snapshot=$(ps -eo pid,comm,%cpu,%mem --sort=-%cpu | head -n 12 || true)
{
echo
echo "=== Top CPU Processes ==="
echo "$top_snapshot"
} >>"$REPORT_FILE"
local xorg_cpu
xorg_cpu=$(ps -C Xorg -o %cpu= | awk '{sum+=$1} END {printf "%.0f", sum+0}' || echo 0)
if [[ ${xorg_cpu:-0} -ge 20 ]]; then
add_finding "Xorg is using high CPU (${xorg_cpu}%); desktop/compositor/GPU driver path may be a primary slowdown source."
fi
}
check_cpu_governor() {
# An ARRAY, not a newline-joined string: the awk/grep calls below need one
# argument per file. With the old unquoted "$gov_files" an empty result
# also left awk with NO file operands, so it fell through to reading stdin
# and the diagnostic hung instead of reporting 'not found'.
local -a gov_files=()
mapfile -t gov_files < <(find /sys/devices/system/cpu -maxdepth 3 -name scaling_governor 2>/dev/null || true)
if ((${#gov_files[@]} == 0)); then
add_action "CPU governor files not found (may be unsupported on this platform)."
return
fi
local summary
summary=$(awk '{count[$1]++} END {for (g in count) printf "%s:%d ", g, count[g]}' "${gov_files[@]}" 2>/dev/null || true)
echo "CPU governor summary: ${summary:-unknown}" >>"$REPORT_FILE"
if grep -q '^powersave$' "${gov_files[@]}" 2>/dev/null; then
add_finding "CPU governor includes 'powersave' on one or more cores; this can make high-end hardware feel slow."
fi
}
check_thermal_state() {
if has_cmd sensors; then
run_and_log "Temperatures (sensors)" sensors
else
add_action "Install lm_sensors and run 'sensors' to verify thermal throttling."
fi
if has_cmd dmesg; then
local therm_hits
therm_hits=$(dmesg | grep -Ei 'throttl|thermal|overheat|cpu clock throttled' | tail -n 30 || true)
if [[ -n $therm_hits ]]; then
add_finding "Kernel logs show thermal/throttling related messages."
{
echo
echo "=== Thermal/Throttling dmesg excerpts ==="
echo "$therm_hits"
} >>"$REPORT_FILE"
fi
fi
}
check_power_services() {
local tlp_enabled="false"
local ppd_enabled="false"
if systemctl is-enabled tlp.service >/dev/null 2>&1; then
tlp_enabled="true"
fi
if systemctl is-enabled power-profiles-daemon.service >/dev/null 2>&1; then
ppd_enabled="true"
fi
echo "Power services: tlp=${tlp_enabled}, power-profiles-daemon=${ppd_enabled}" >>"$REPORT_FILE"
if [[ $tlp_enabled == "true" && $ppd_enabled == "true" ]]; then
add_finding "Both TLP and power-profiles-daemon are enabled; they often conflict and cause inconsistent performance."
fi
if [[ $tlp_enabled == "false" && $ppd_enabled == "false" ]]; then
add_action "No power management daemon is enabled; consider installing/enabling power-profiles-daemon for predictable AC/battery behavior."
fi
}
check_storage_health() {
run_and_log "Block Devices" lsblk -o NAME,MODEL,ROTA,SIZE,TYPE,MOUNTPOINT,FSTYPE
if has_cmd fstrim; then
run_and_log "fstrim dry-run" fstrim -av --dry-run
fi
if systemctl is-enabled fstrim.timer >/dev/null 2>&1; then
add_action "fstrim.timer is enabled (good for SSD performance longevity)."
else
add_finding "fstrim.timer is not enabled; SSD maintenance trimming may be missing."
fi
if has_cmd smartctl; then
local root_disk
root_disk=$(findmnt -n -o SOURCE / | sed 's/[0-9]*$//' | sed 's/p$//' || true)
if [[ -n ${root_disk:-} && -b $root_disk ]]; then
run_and_log "SMART Summary ($root_disk)" smartctl -H "$root_disk"
fi
else
add_action "Install smartmontools and run SMART health checks for your SSD/NVMe."
fi
}
check_memory_pressure() {
local mem_total mem_available swap_total swap_free
mem_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
mem_available=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
swap_total=$(awk '/SwapTotal/ {print $2}' /proc/meminfo)
swap_free=$(awk '/SwapFree/ {print $2}' /proc/meminfo)
if [[ ${swap_total:-0} -gt 0 ]]; then
local swap_used
swap_used=$((swap_total - swap_free))
local swap_pct
swap_pct=$((swap_used * 100 / swap_total))
echo "Swap usage: ${swap_pct}%" >>"$REPORT_FILE"
if [[ $swap_pct -ge 35 && ${mem_available:-0} -gt $((mem_total / 3)) ]]; then
add_finding "High swap usage while RAM is still available; this can cause stutter."
add_action "Consider lowering swappiness (temporary: sudo sysctl vm.swappiness=10)."
fi
fi
if [[ -f /proc/pressure/memory ]]; then
run_and_log "Memory PSI" cat /proc/pressure/memory
fi
}

View File

@ -0,0 +1,103 @@
#!/bin/bash
# GPU and journal probes, the safe-fix pass and the report summary.
#
# Sourced by diagnose_arch_performance.sh; split out to keep
# arch_perf_probes.sh under the 250-line cap. Sourced rather than run, so
# it inherits the caller's strict mode and the variables above the source.
check_gpu_state() {
if has_cmd nvidia-smi; then
run_and_log "NVIDIA State" nvidia-smi
local pstate util power
pstate=$(nvidia-smi --query-gpu=pstate --format=csv,noheader 2>/dev/null | head -n 1 | xargs || true)
util=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 | xargs || true)
power=$(nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits 2>/dev/null | head -n 1 | xargs || true)
{
echo "NVIDIA pstate: ${pstate:-unknown}"
echo "NVIDIA util: ${util:-unknown}%"
echo "NVIDIA power: ${power:-unknown}W"
} >>"$REPORT_FILE"
if [[ ${pstate:-} == "P0" && ${util:-100} -le 5 ]]; then
add_finding "NVIDIA GPU is in P0 high-performance state while mostly idle; this can increase heat and trigger thermal limits."
add_action "If laptop has hybrid graphics, prefer iGPU mode for desktop workloads and use dGPU on demand."
fi
else
run_and_log "PCI VGA Devices" lspci -nnk | grep -A3 -Ei 'vga|3d|display'
fi
}
check_journal_size() {
local journal_line
journal_line=$(journalctl --disk-usage 2>/dev/null || true)
echo "Journal usage: ${journal_line:-unknown}" >>"$REPORT_FILE"
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ (G|M) ]]; then
local value unit
value="${BASH_REMATCH[1]}"
unit="${BASH_REMATCH[2]}"
if [[ $unit == "G" ]]; then
add_finding "Systemd journal is large (${value}G); excessive logs can waste I/O and disk space."
fi
fi
}
apply_safe_fixes() {
if [[ $APPLY_SAFE_FIXES != "true" ]]; then
return
fi
log_info "Applying safe fixes..."
if ! systemctl is-enabled fstrim.timer >/dev/null 2>&1; then
systemctl enable --now fstrim.timer
add_action "Enabled and started fstrim.timer."
fi
if systemctl is-enabled tlp.service >/dev/null 2>&1 && systemctl is-enabled power-profiles-daemon.service >/dev/null 2>&1; then
systemctl disable --now tlp.service
add_action "Disabled tlp.service to avoid conflict with power-profiles-daemon."
fi
local journal_line
journal_line=$(journalctl --disk-usage 2>/dev/null || true)
if [[ $journal_line =~ ([0-9]+\.?[0-9]*)\ G ]]; then
journalctl --vacuum-size=300M
add_action "Vacuumed systemd journal to 300M."
fi
}
print_summary() {
echo
echo "=============================="
echo " Arch Performance Diagnostics"
echo "=============================="
echo "Report: $REPORT_FILE"
echo
if [[ ${#FINDINGS[@]} -eq 0 ]]; then
log_ok "No high-confidence bottlenecks detected by automated checks."
else
log_warn "Likely issues found (${#FINDINGS[@]}):"
local item
for item in "${FINDINGS[@]}"; do
echo " - $item"
done
fi
if [[ ${#ACTIONS[@]} -gt 0 ]]; then
echo
log_info "Actions/recommendations:"
local action
for action in "${ACTIONS[@]}"; do
echo " - $action"
done
fi
echo
echo "Recommended next command for deep per-process analysis:"
echo " sudo iotop -oPa"
echo " top"
echo " systemd-analyze blame"
}

View File

@ -0,0 +1,179 @@
#!/bin/bash
# Individual Thorium profile repairs: state, locks, caches.
#
# Sourced by fix_thorium.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# Fix 1: Handle corrupted Local State file (most common crash cause)
fix_local_state() {
log_info "Checking Local State file..."
local local_state="$THORIUM_CONFIG_DIR/Local State"
if [[ -f $local_state ]]; then
# Check if it's valid JSON
if ! python3 -c "import json; json.load(open('$local_state'))" 2> /dev/null; then
log_warn "Local State file appears corrupted"
backup_if_exists "$local_state"
else
# Even if valid JSON, back it up as it can still cause crashes
log_info "Local State exists - backing up (common crash source)"
backup_if_exists "$local_state"
fi
else
log_info "No Local State file found (OK for fresh install)"
fi
}
# Fix 2: Clear singleton lock files
fix_singleton_locks() {
log_info "Clearing singleton lock files..."
local locks=(
"$THORIUM_CONFIG_DIR/SingletonLock"
"$THORIUM_CONFIG_DIR/SingletonSocket"
"$THORIUM_CONFIG_DIR/SingletonCookie"
)
local cleared=0
for lock in "${locks[@]}"; do
if remove_if_exists "$lock"; then
((cleared++)) || true
fi
done
if [[ $cleared -eq 0 ]]; then
log_info "No stale lock files found"
fi
}
# Fix 3: Clear GPU cache
fix_gpu_cache() {
log_info "Clearing GPU cache..."
local gpu_paths=(
"$THORIUM_CONFIG_DIR/GPUCache"
"$THORIUM_CONFIG_DIR/Default/GPUCache"
"$THORIUM_CONFIG_DIR/ShaderCache"
"$THORIUM_CONFIG_DIR/Default/ShaderCache"
)
local cleared=0
for cache in "${gpu_paths[@]}"; do
if remove_if_exists "$cache"; then
((cleared++)) || true
fi
done
if [[ $cleared -eq 0 ]]; then
log_info "No GPU cache to clear"
fi
}
# Fix 4: Clear crash reports (can accumulate and cause issues)
fix_crash_reports() {
log_info "Clearing old crash reports..."
local crash_dir="$THORIUM_CONFIG_DIR/Crash Reports"
if [[ -d $crash_dir ]]; then
local crash_count
crash_count=$(find "$crash_dir" -type f 2> /dev/null | wc -l)
if [[ $crash_count -gt 0 ]]; then
if [[ $DRY_RUN == true ]]; then
echo " [dry-run] Would clear $crash_count crash report(s)"
else
rm -rf "$crash_dir"
log_ok "Cleared $crash_count crash report(s)"
fi
fi
fi
}
# Fix 5: Aggressive cleaning (optional)
fix_aggressive() {
if [[ $AGGRESSIVE != true ]]; then
return
fi
log_warn "Applying aggressive fixes (may lose some site data)..."
local aggressive_paths=(
"$THORIUM_CONFIG_DIR/Default/Service Worker"
"$THORIUM_CONFIG_DIR/Default/Cache"
"$THORIUM_CONFIG_DIR/Default/Code Cache"
"$THORIUM_CONFIG_DIR/Default/IndexedDB"
"$THORIUM_CONFIG_DIR/BrowserMetrics"
"$THORIUM_CONFIG_DIR/component_crx_cache"
)
for path in "${aggressive_paths[@]}"; do
remove_if_exists "$path"
done
# Backup potentially corrupted databases
local db_files=(
"$THORIUM_CONFIG_DIR/Default/Web Data"
"$THORIUM_CONFIG_DIR/Default/History"
)
for db in "${db_files[@]}"; do
if [[ -f $db ]]; then
log_info "Checking database: $(basename "$db")"
# Simple corruption check - if sqlite3 can't open it, back it up
if command -v sqlite3 &> /dev/null; then
if ! sqlite3 "$db" "PRAGMA integrity_check;" &> /dev/null; then
log_warn "Database may be corrupted: $(basename "$db")"
backup_if_exists "$db"
fi
fi
fi
done
}
# Test if Thorium starts successfully
test_thorium() {
if [[ $TEST_AFTER != true ]]; then
return
fi
log_info "Testing Thorium startup..."
if [[ $DRY_RUN == true ]]; then
echo " [dry-run] Would test thorium-browser startup"
return
fi
# Start Thorium in background
thorium-browser &> /dev/null &
local pid=$!
# Wait a few seconds and check if it's still running
sleep 4
if kill -0 "$pid" 2> /dev/null; then
log_ok "Thorium started successfully! (PID: $pid)"
echo -e "${GREEN}Fix successful!${NC} Thorium is now running."
# Offer to keep it running or kill it
read -r -p "Keep browser running? [Y/n] " response
case "$response" in
[nN]*)
kill "$pid" 2> /dev/null || true
log_info "Browser closed"
;;
*)
log_info "Browser left running"
;;
esac
else
log_error "Thorium still crashing after fixes"
echo -e "${RED}Standard fixes did not resolve the issue.${NC}"
echo ""
echo "Try these additional steps:"
echo " 1. Run with --aggressive flag for deeper cleaning"
echo " 2. Test with fresh profile: thorium-browser --user-data-dir=/tmp/thorium-test"
echo " 3. Reinstall: yay -S thorium-browser-bin"
echo " 4. Check NVIDIA drivers: nvidia-smi"
exit 1
fi
}
# Main execution

View File

@ -104,8 +104,8 @@ ensure_deps_arch() {
fi
}
desktop_dir="$HOME/.local/share/applications"
mkdir -p "$desktop_dir"
DESKTOP_DIR="$HOME/.local/share/applications"
mkdir -p "$DESKTOP_DIR"
detect_unityhub() {
# Outputs: INSTALL_TYPE (FLATPAK|NATIVE|APPIMAGE|UNKNOWN) and EXEC_CMD
@ -194,74 +194,8 @@ detect_unityhub() {
echo "$install_type|$exec_cmd"
}
create_handler_desktop() {
local exec_cmd="$1"
local dest="$desktop_dir/unityhub-url-handler.desktop"
log_info "Writing handler desktop entry: $dest"
cat >"$dest" <<DESK
[Desktop Entry]
Name=Unity Hub URL Handler
Comment=Handle unityhub:// links for Unity Hub sign-in
Exec=${exec_cmd}
Terminal=false
Type=Application
Icon=unityhub
Categories=Development;
StartupWMClass=Unity Hub
MimeType=x-scheme-handler/unityhub;x-scheme-handler/unity;
NoDisplay=true
DESK
log_ok "Desktop entry created/updated."
echo "$dest"
}
register_mime_handler() {
local desktop_file="$1"
# Update desktop database if available
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database "$desktop_dir" || true
else
log_warn "update-desktop-database not found (install desktop-file-utils)."
fi
# Register as default handler for both schemes
if command -v xdg-mime >/dev/null 2>&1; then
xdg-mime default "$(basename "$desktop_file")" x-scheme-handler/unityhub || true
xdg-mime default "$(basename "$desktop_file")" x-scheme-handler/unity || true
else
log_error "xdg-mime not found (install xdg-utils)."
return 1
fi
log_ok "MIME handler registered for unityhub:// (and unity://)."
}
verify_registration() {
local expected cur1 cur2
expected="$(basename "$1")"
cur1="$(xdg-mime query default x-scheme-handler/unityhub 2>/dev/null || true)"
cur2="$(xdg-mime query default x-scheme-handler/unity 2>/dev/null || true)"
log_info "Current handler (unityhub): ${cur1:-<none>}"
log_info "Current handler (unity): ${cur2:-<none>}"
if [[ $cur1 == "$expected" ]]; then
log_ok "unityhub scheme correctly set to $expected"
else
log_warn "unityhub scheme not set to $expected (currently: ${cur1:-none})."
fi
}
maybe_test_open() {
if [[ $RUN_TEST == true ]]; then
log_info "Opening test link: unityhub://v1/editor-signin"
if command -v xdg-open >/dev/null 2>&1; then
xdg-open 'unityhub://v1/editor-signin' >/dev/null 2>&1 || true
log_ok "Test link invoked. Check if Unity Hub launches or focuses."
else
log_warn "xdg-open not found; cannot run test automatically."
fi
else
log_info "You can test manually with: xdg-open 'unityhub://v1/editor-signin'"
fi
}
# shellcheck source=lib/unity_handler.sh
source "$SCRIPT_DIR/lib/unity_handler.sh"
main() {
log_info "Ensuring required tools (optional)."

View File

@ -0,0 +1,75 @@
#!/bin/bash
# Desktop entry, MIME registration and verification for Unity Hub.
#
# Sourced by fix_unity.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
create_handler_desktop() {
local exec_cmd="$1"
local dest="$DESKTOP_DIR/unityhub-url-handler.desktop"
log_info "Writing handler desktop entry: $dest"
cat >"$dest" <<DESK
[Desktop Entry]
Name=Unity Hub URL Handler
Comment=Handle unityhub:// links for Unity Hub sign-in
Exec=${exec_cmd}
Terminal=false
Type=Application
Icon=unityhub
Categories=Development;
StartupWMClass=Unity Hub
MimeType=x-scheme-handler/unityhub;x-scheme-handler/unity;
NoDisplay=true
DESK
log_ok "Desktop entry created/updated."
echo "$dest"
}
register_mime_handler() {
local desktop_file="$1"
# Update desktop database if available
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database "$DESKTOP_DIR" || true
else
log_warn "update-desktop-database not found (install desktop-file-utils)."
fi
# Register as default handler for both schemes
if command -v xdg-mime >/dev/null 2>&1; then
xdg-mime default "$(basename "$desktop_file")" x-scheme-handler/unityhub || true
xdg-mime default "$(basename "$desktop_file")" x-scheme-handler/unity || true
else
log_error "xdg-mime not found (install xdg-utils)."
return 1
fi
log_ok "MIME handler registered for unityhub:// (and unity://)."
}
verify_registration() {
local expected cur1 cur2
expected="$(basename "$1")"
cur1="$(xdg-mime query default x-scheme-handler/unityhub 2>/dev/null || true)"
cur2="$(xdg-mime query default x-scheme-handler/unity 2>/dev/null || true)"
log_info "Current handler (unityhub): ${cur1:-<none>}"
log_info "Current handler (unity): ${cur2:-<none>}"
if [[ $cur1 == "$expected" ]]; then
log_ok "unityhub scheme correctly set to $expected"
else
log_warn "unityhub scheme not set to $expected (currently: ${cur1:-none})."
fi
}
maybe_test_open() {
if [[ $RUN_TEST == true ]]; then
log_info "Opening test link: unityhub://v1/editor-signin"
if command -v xdg-open >/dev/null 2>&1; then
xdg-open 'unityhub://v1/editor-signin' >/dev/null 2>&1 || true
log_ok "Test link invoked. Check if Unity Hub launches or focuses."
else
log_warn "xdg-open not found; cannot run test automatically."
fi
else
log_info "You can test manually with: xdg-open 'unityhub://v1/editor-signin'"
fi
}

View File

@ -112,201 +112,9 @@ confirm() {
esac
}
parse_args() {
DEVICE=""
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run)
DRY_RUN=true
shift
;;
--fs)
if [[ $# -lt 2 ]]; then
echo "Missing value for --fs" >&2
exit 1
fi
FILESYSTEM="$2"
shift 2
;;
--dumbphone)
# Force settings that are friendlier to older phones:
# * MBR (dos) partition table
# * Single ~30GiB FAT32 partition
# * Leave remaining space unused
DUMBPHONE_MODE=true
FILESYSTEM="vfat"
shift
;;
-h | --help)
usage
exit 0
;;
/dev/*)
DEVICE="$1"
shift
;;
*)
echo "Unknown argument: $1" >&2
usage
exit 1
;;
esac
done
export DEVICE FILESYSTEM DRY_RUN DUMBPHONE_MODE
}
detect_sd_card() {
# List removable disks (RM=1, TYPE=disk)
# Columns: NAME, RM, SIZE, MODEL, TRAN, TYPE
local output
output=$(lsblk -o NAME,RM,SIZE,MODEL,TRAN,TYPE -nr | awk '$2==1 && $6=="disk"') || true
if [[ -z $output ]]; then
echo "No removable disks detected. Please provide device explicitly (e.g., /dev/sda)." >&2
exit 1
fi
mapfile -t candidates < <(echo "$output")
if [[ ${#candidates[@]} -eq 1 ]]; then
local name size model tran
read -r name _ size model tran _ <<< "${candidates[0]}"
DEVICE="/dev/${name}"
log "Detected removable disk: $DEVICE (${size} ${model} ${tran})"
else
echo "Multiple removable disks detected:" >&2
local i=1
for line in "${candidates[@]}"; do
local name size model tran
read -r name _ size model tran _ <<< "$line"
printf ' %d) /dev/%s %s %s %s\n' "$i" "$name" "$size" "$model" "$tran"
((i++))
done
while true; do
read -r -p "Select device to format (1-${#candidates[@]}): " choice
if [[ $choice =~ ^[0-9]+$ ]] && ((choice >= 1 && choice <= ${#candidates[@]})); then
local sel="${candidates[choice - 1]}"
local name size model tran
read -r name _ size model tran _ <<< "$sel"
DEVICE="/dev/${name}"
log "Selected device: $DEVICE (${size} ${model} ${tran})"
break
else
echo "Invalid choice." >&2
fi
done
fi
}
validate_device() {
if [[ -z ${DEVICE:-} ]]; then
detect_sd_card
fi
if [[ ! -b $DEVICE ]]; then
echo "Device $DEVICE does not exist or is not a block device." >&2
exit 1
fi
# Extra safety: refuse clearly system disks by checking if rootfs lives there
local root_dev
root_dev=$(findmnt -no SOURCE / || true)
if [[ $root_dev == "$DEVICE"* ]]; then
echo "Refusing to operate on $DEVICE because it appears to contain the root filesystem ($root_dev)." >&2
exit 1
fi
}
unmount_partitions() {
local dev base part
dev="$DEVICE"
base="${dev##*/}"
mapfile -t parts < <(lsblk -nr -o NAME,MOUNTPOINT "/dev/${base}" | awk 'NF==2 {print $1" "$2}') || true
for entry in "${parts[@]:-}"; do
read -r part mp <<< "$entry"
if [[ -n $mp ]]; then
run "umount \"$mp\""
fi
done
}
wipe_and_partition() {
local dev="$DEVICE"
if ! confirm "About to WIPE ALL DATA on $dev and create a new ${FILESYSTEM} filesystem. Continue?"; then
echo "Aborted by user." >&2
exit 1
fi
# Zap existing partition table
run "wipefs -a \"$dev\""
# Create a new partition table + partition layout
# Using sfdisk for non-interactive, reproducible layout
local sfdisk_input
if [[ $DUMBPHONE_MODE == true ]]; then
# Old phones often:
# * only support MBR (dos)
# * only support SD/SDHC (<=32GiB)
# We create an MBR table and a single ~30GiB FAT32 partition, leaving the rest unused.
# 30GiB ≈ 30 * 2^30 / 512 ≈ 62914560 sectors; start at 2048 for alignment.
sfdisk_input=$'label: dos\n2048,62914560,c,*\n'
if [[ $DRY_RUN == true ]]; then
log "DRY RUN: echo -e '$sfdisk_input' | sfdisk $dev"
else
log "RUN: create MBR (dos) with ~30GiB FAT32 partition on $dev"
echo -e "$sfdisk_input" | sfdisk "$dev"
fi
else
# Default: GPT with one partition spanning the whole device
sfdisk_input=$'label: gpt\n,;\n'
if [[ $DRY_RUN == true ]]; then
log "DRY RUN: echo -e '$sfdisk_input' | sfdisk $dev"
else
log "RUN: create GPT with one partition on $dev"
echo -e "$sfdisk_input" | sfdisk "$dev"
fi
fi
# Let the kernel re-read the partition table
sleep 2
}
format_filesystem() {
local dev base part
dev="$DEVICE"
base="${dev##*/}"
part="/dev/${base}1"
if [[ ! -b $part ]]; then
echo "Expected partition $part not found after partitioning." >&2
exit 1
fi
case "$FILESYSTEM" in
exfat)
run mkfs.exfat -n SDCARD "$part"
;;
vfat | fat32)
run mkfs.vfat -F32 -n SDCARD "$part"
;;
ext4)
run mkfs.ext4 -F -L SDCARD "$part"
;;
*)
echo "Unsupported filesystem type: $FILESYSTEM" >&2
exit 1
;;
esac
log "Formatting completed on $part with filesystem $FILESYSTEM."
}
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/sd_card_ops.sh
source "$SCRIPT_DIR/lib/sd_card_ops.sh"
main() {
parse_args "$@"

View File

@ -117,166 +117,10 @@ install_exercism_cli() {
fi
}
# Configure exercism workspace
configure_exercism() {
echo ""
echo "=== Configuring Exercism ==="
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/exercism_config.sh
source "$SCRIPT_DIR/lib/exercism_config.sh"
mkdir -p "$EXERCISM_DIR"
# Check if already configured
if exercism configure 2>&1 | grep -q "workspace"; then
success "Exercism already configured"
else
# Set workspace directory
exercism configure --workspace="$EXERCISM_DIR"
success "Workspace set to: $EXERCISM_DIR"
fi
echo ""
info "To fully configure Exercism with your account:"
echo " 1. Create free account at https://exercism.org"
echo " 2. Go to https://exercism.org/settings/api_cli"
echo " 3. Copy your API token"
echo " 4. Run: exercism configure --token=YOUR_TOKEN"
echo ""
}
# Install test runners for languages
install_test_runners() {
echo ""
echo "=== Installing Test Runners ==="
echo ""
# Python - pytest
if command -v python3 &>/dev/null; then
if python3 -c "import pytest" 2>/dev/null; then
success "Python: pytest already installed"
else
info "Installing pytest for Python exercises..."
if pip3 install --user pytest 2>/dev/null; then
success "Python: pytest installed"
else
warn "Python: install pytest manually"
fi
fi
fi
# JavaScript/TypeScript - Node.js + npm
if command -v node &>/dev/null; then
success "JavaScript/TypeScript: Node.js available ($(node --version))"
info " Tests run with: npm test (or jest)"
else
warn "JavaScript/TypeScript: Install Node.js for JS/TS exercises"
fi
# C - gcc + criterion/cmocka
if command -v gcc &>/dev/null; then
success "C: gcc available"
info " Some C exercises use Unity test framework (included in exercise)"
else
warn "C: Install gcc for C exercises"
fi
# C++ - g++ + Catch2/doctest
if command -v g++ &>/dev/null; then
success "C++: g++ available"
info " C++ exercises use Catch2 (header-only, included in exercise)"
else
warn "C++: Install g++ for C++ exercises"
fi
# Rust
if command -v cargo &>/dev/null; then
success "Rust: cargo available (tests with: cargo test)"
fi
# Go
if command -v go &>/dev/null; then
success "Go: go available (tests with: go test)"
fi
}
# Download exercises for a track (language)
download_track() {
local track="$1"
local count="${2:-10}"
echo ""
info "Downloading $count exercises for $track track..."
# Get list of exercises
local exercises
exercises=$(curl -fsSL "https://exercism.org/api/v2/tracks/${track}/exercises" 2>/dev/null |
grep -oP '"slug":"\K[^"]+' | head -n "$count")
if [[ -z $exercises ]]; then
warn "Could not fetch exercise list for $track"
return 1
fi
local downloaded=0
for exercise in $exercises; do
local exercise_dir="$EXERCISM_DIR/$track/$exercise"
if [[ -d $exercise_dir ]]; then
echo " [exists] $exercise"
else
if exercism download --track="$track" --exercise="$exercise" 2>/dev/null; then
echo " [downloaded] $exercise"
((downloaded++))
else
echo " [failed] $exercise (may require auth)"
fi
fi
done
success "Downloaded $downloaded new exercises for $track"
}
# Show available tracks and usage
show_usage() {
echo ""
echo "=============================================="
echo " Exercism Usage Guide"
echo "=============================================="
echo ""
echo -e "${CYAN}Download exercises:${NC}"
echo " exercism download --track=python --exercise=hello-world"
echo " exercism download --track=javascript --exercise=two-fer"
echo " exercism download --track=c --exercise=isogram"
echo ""
echo -e "${CYAN}Run tests locally:${NC}"
echo " Python: cd ~/exercism/python/hello-world && pytest"
echo " JavaScript: cd ~/exercism/javascript/hello-world && npm test"
echo " TypeScript: cd ~/exercism/typescript/hello-world && npm test"
echo " C: cd ~/exercism/c/hello-world && make test"
echo " C++: cd ~/exercism/cpp/hello-world && make"
echo " Rust: cd ~/exercism/rust/hello-world && cargo test"
echo " Go: cd ~/exercism/go/hello-world && go test"
echo ""
echo -e "${CYAN}Submit solution (when online):${NC}"
echo " exercism submit solution.py"
echo ""
echo -e "${CYAN}Popular tracks:${NC}"
echo " python, javascript, typescript, c, cpp, rust, go, java, ruby"
echo " bash, elixir, haskell, kotlin, swift, csharp, php, sql"
echo ""
echo -e "${CYAN}Batch download (requires API token):${NC}"
echo " # Download first 20 Python exercises:"
# Example commands printed for the user to copy; $(...) and $ex must stay
# literal rather than execute here.
# shellcheck disable=SC2016
echo ' for ex in $(exercism download --track=python 2>&1 | head -20); do'
# shellcheck disable=SC2016
echo ' exercism download --track=python --exercise=$ex'
echo " done"
echo ""
echo "Exercises are in: $EXERCISM_DIR"
echo ""
echo "=============================================="
}
# Main
main() {
# Step 1: Install CLI
echo ""

View File

@ -0,0 +1,167 @@
#!/bin/bash
# Exercism CLI configuration and per-track test runners.
#
# Sourced by install_exercism.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
# Configure exercism workspace
configure_exercism() {
echo ""
echo "=== Configuring Exercism ==="
mkdir -p "$EXERCISM_DIR"
# Check if already configured
if exercism configure 2>&1 | grep -q "workspace"; then
success "Exercism already configured"
else
# Set workspace directory
exercism configure --workspace="$EXERCISM_DIR"
success "Workspace set to: $EXERCISM_DIR"
fi
echo ""
info "To fully configure Exercism with your account:"
echo " 1. Create free account at https://exercism.org"
echo " 2. Go to https://exercism.org/settings/api_cli"
echo " 3. Copy your API token"
echo " 4. Run: exercism configure --token=YOUR_TOKEN"
echo ""
}
# Install test runners for languages
install_test_runners() {
echo ""
echo "=== Installing Test Runners ==="
echo ""
# Python - pytest
if command -v python3 &>/dev/null; then
if python3 -c "import pytest" 2>/dev/null; then
success "Python: pytest already installed"
else
info "Installing pytest for Python exercises..."
if pip3 install --user pytest 2>/dev/null; then
success "Python: pytest installed"
else
warn "Python: install pytest manually"
fi
fi
fi
# JavaScript/TypeScript - Node.js + npm
if command -v node &>/dev/null; then
success "JavaScript/TypeScript: Node.js available ($(node --version))"
info " Tests run with: npm test (or jest)"
else
warn "JavaScript/TypeScript: Install Node.js for JS/TS exercises"
fi
# C - gcc + criterion/cmocka
if command -v gcc &>/dev/null; then
success "C: gcc available"
info " Some C exercises use Unity test framework (included in exercise)"
else
warn "C: Install gcc for C exercises"
fi
# C++ - g++ + Catch2/doctest
if command -v g++ &>/dev/null; then
success "C++: g++ available"
info " C++ exercises use Catch2 (header-only, included in exercise)"
else
warn "C++: Install g++ for C++ exercises"
fi
# Rust
if command -v cargo &>/dev/null; then
success "Rust: cargo available (tests with: cargo test)"
fi
# Go
if command -v go &>/dev/null; then
success "Go: go available (tests with: go test)"
fi
}
# Download exercises for a track (language)
download_track() {
local track="$1"
local count="${2:-10}"
echo ""
info "Downloading $count exercises for $track track..."
# Get list of exercises
local exercises
exercises=$(curl -fsSL "https://exercism.org/api/v2/tracks/${track}/exercises" 2>/dev/null |
grep -oP '"slug":"\K[^"]+' | head -n "$count")
if [[ -z $exercises ]]; then
warn "Could not fetch exercise list for $track"
return 1
fi
local downloaded=0
for exercise in $exercises; do
local exercise_dir="$EXERCISM_DIR/$track/$exercise"
if [[ -d $exercise_dir ]]; then
echo " [exists] $exercise"
else
if exercism download --track="$track" --exercise="$exercise" 2>/dev/null; then
echo " [downloaded] $exercise"
((downloaded++))
else
echo " [failed] $exercise (may require auth)"
fi
fi
done
success "Downloaded $downloaded new exercises for $track"
}
# Show available tracks and usage
show_usage() {
echo ""
echo "=============================================="
echo " Exercism Usage Guide"
echo "=============================================="
echo ""
echo -e "${CYAN}Download exercises:${NC}"
echo " exercism download --track=python --exercise=hello-world"
echo " exercism download --track=javascript --exercise=two-fer"
echo " exercism download --track=c --exercise=isogram"
echo ""
echo -e "${CYAN}Run tests locally:${NC}"
echo " Python: cd ~/exercism/python/hello-world && pytest"
echo " JavaScript: cd ~/exercism/javascript/hello-world && npm test"
echo " TypeScript: cd ~/exercism/typescript/hello-world && npm test"
echo " C: cd ~/exercism/c/hello-world && make test"
echo " C++: cd ~/exercism/cpp/hello-world && make"
echo " Rust: cd ~/exercism/rust/hello-world && cargo test"
echo " Go: cd ~/exercism/go/hello-world && go test"
echo ""
echo -e "${CYAN}Submit solution (when online):${NC}"
echo " exercism submit solution.py"
echo ""
echo -e "${CYAN}Popular tracks:${NC}"
echo " python, javascript, typescript, c, cpp, rust, go, java, ruby"
echo " bash, elixir, haskell, kotlin, swift, csharp, php, sql"
echo ""
echo -e "${CYAN}Batch download (requires API token):${NC}"
echo " # Download first 20 Python exercises:"
# Example commands printed for the user to copy; $(...) and $ex must stay
# literal rather than execute here.
# shellcheck disable=SC2016
echo ' for ex in $(exercism download --track=python 2>&1 | head -20); do'
# shellcheck disable=SC2016
echo ' exercism download --track=python --exercise=$ex'
echo " done"
echo ""
echo "Exercises are in: $EXERCISM_DIR"
echo ""
echo "=============================================="
}
# Main

View File

@ -0,0 +1,122 @@
#!/bin/bash
# Idle-inhibit process and the controller-connection watchers.
#
# Sourced by turn_off_auto_idle_screen_shutdown.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
start_idle_inhibit() {
# Hold one systemd idle inhibitor for the whole time a controller is
# connected. This replaces the previous per-event fork storm (4 xset + an
# xdotool + a dd read + a sleep on *every* joystick event, ~21 forks/s while
# gaming): a single long-lived process keeps logind from treating the session
# as idle (so it won't auto-suspend or lock), while X11 blanking stays off
# thanks to the one-shot disable_x11_idle above. Idempotent — a live inhibitor
# is reused.
if [[ -n $inhibit_pid ]] && kill -0 "$inhibit_pid" 2> /dev/null; then
return 0
fi
# NOTE: --what=idle only (NOT idle:sleep). An idle inhibitor already stops
# logind's idle-triggered auto-suspend/lock — which is all gaming needs — but
# a *sleep* inhibitor would also block *deliberate* suspend/hibernate, e.g.
# the scheduled digital-wellbeing day-specific-shutdown hibernate. Blocking
# sleep here once silently kept the PC running past every shutdown window.
systemd-inhibit --what=idle --who="idle-off" \
--why="game controller connected" sleep infinity &
inhibit_pid=$!
log "Holding idle inhibitor (pid ${inhibit_pid}) while a controller is connected"
}
stop_idle_inhibit() {
if [[ -z $inhibit_pid ]]; then
return 0
fi
kill "$inhibit_pid" 2> /dev/null || true
wait "$inhibit_pid" 2> /dev/null || true
inhibit_pid=""
log "Released idle inhibitor; normal idle behaviour resumes"
}
controller_connected() {
# Pure-bash glob check — zero forks. True if any /dev/input/js* node exists.
local dev
for dev in /dev/input/js*; do
[[ -e $dev ]] && return 0
done
return 1
}
sync_inhibit_to_controllers() {
# Hold the inhibitor exactly when a controller is present.
if controller_connected; then
start_idle_inhibit
else
stop_idle_inhibit
fi
}
start_controller_watchers() {
# Event-driven and fork-free in the hot path: react only to input-device
# add/remove (rare udev events), never to individual joystick *input* events,
# and hold a single systemd-inhibit lock while a controller is present.
if ! has_cmd systemd-inhibit; then
warn "systemd-inhibit not found; cannot hold an idle inhibitor"
return 0
fi
# EXIT covers every termination path (including a SIGTERM that interrupts the
# blocking read below); INT/TERM additionally give a clean exit status.
trap 'stop_idle_inhibit' EXIT
trap 'exit 0' INT TERM
sync_inhibit_to_controllers # apply current state once at startup
if has_cmd udevadm; then
log "Watching controller hotplug via udev (no polling)"
# Process substitution (not a pipe) keeps the loop in this shell so
# inhibit_pid persists across events.
while read -r _; do
sync_inhibit_to_controllers
done < <(udevadm monitor --udev --subsystem-match=input 2> /dev/null)
else
# Fallback when udevadm is unavailable: a low-frequency presence poll. One
# sleep per 30 s cycle (~0.03 forks/s) versus the old ~21 forks/s.
warn "udevadm not found; falling back to a 30 s presence poll"
while :; do
sync_inhibit_to_controllers
sleep 30
done
fi
}
persist_with_systemd_logind() {
# Set IdleAction=ignore in /etc/systemd/logind.conf and restart logind
# Warning: restarting logind can affect user sessions (e.g., inhibit handling). Use with care.
# Takes the flag as an argument rather than reading the caller's global, so
# this file is checkable on its own.
local persist="${1:-false}"
if [[ $persist != true ]]; then
return 0
fi
if ! has_cmd sudo; then
warn "sudo not found; cannot persist systemd-logind setting"
return 0
fi
log "Persisting: setting systemd-logind IdleAction=ignore (requires sudo)"
sudo sh -c '
set -e
conf=/etc/systemd/logind.conf
if [ ! -f "$conf" ]; then
touch "$conf"
fi
# Backup once
[ -f "${conf}.bak" ] || cp -a "$conf" "${conf}.bak"
# Ensure the key exists and is set to ignore
if grep -q "^#\?IdleAction=" "$conf"; then
sed -i "s/^#\?IdleAction=.*/IdleAction=ignore/" "$conf"
else
printf "\nIdleAction=ignore\n" >> "$conf"
fi
'
log "Restarting systemd-logind to apply changes (may briefly affect session inhibitors)"
sudo systemctl restart systemd-logind || warn "Failed to restart systemd-logind"
}

View File

@ -0,0 +1,215 @@
#!/bin/bash
# Dependency checks and the per-repo study-material steps.
#
# Sourced by repo_to_study.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
#==============================================================================
# Check Dependencies
#==============================================================================
check_dependencies() {
local missing=()
# Check for required scripts
if [ ! -x "$ANALYZE_SCRIPT" ]; then
missing+=("analyze_repo.sh not found at $ANALYZE_SCRIPT")
fi
if [ ! -x "$STUDY_SCRIPT" ]; then
missing+=("generate_study_materials.sh not found at $STUDY_SCRIPT")
fi
# Check for basic tools
for cmd in git curl grep sed awk; do
if ! command -v "$cmd" &>/dev/null; then
missing+=("$cmd")
fi
done
if [ ${#missing[@]} -gt 0 ]; then
print_error "Missing dependencies:"
for dep in "${missing[@]}"; do
echo " - $dep"
done
exit 1
fi
}
#==============================================================================
# Ensure Offline Docs are Available
#==============================================================================
ensure_offline_docs() {
local docs_dir="$HOME/.local/share/offline-docs"
if [ ! -d "$docs_dir/python" ]; then
print_info "Offline docs not found. Setting up Python documentation..."
if [ -x "$SETUP_DOCS_SCRIPT" ]; then
"$SETUP_DOCS_SCRIPT" --python
else
print_info "Run setup_offline_docs.sh --all to enable offline documentation"
fi
fi
}
# Global to store repo name for cloned repos
REPO_NAME=""
#==============================================================================
# Get Repository
#==============================================================================
get_repo() {
local input="$1"
local repo_dir=""
# Check if it's a URL (git clone needed)
if [[ $input =~ ^https?:// ]] || [[ $input =~ ^git@ ]]; then
print_step "Cloning repository..."
# Extract repo name from URL
REPO_NAME=$(basename "$input" .git)
repo_dir="$WORK_DIR/$REPO_NAME"
mkdir -p "$WORK_DIR"
if git clone --depth 1 "$input" "$repo_dir" >&2 2>&1; then
print_success "Cloned: $input"
else
print_error "Failed to clone repository"
exit 1
fi
echo "$repo_dir"
# Local path
elif [ -d "$input" ]; then
# Convert to absolute path
repo_dir="$(cd "$input" && pwd)"
REPO_NAME=$(basename "$repo_dir")
print_success "Using local repository: $repo_dir"
echo "$repo_dir"
else
print_error "Invalid input: '$input' is not a valid URL or directory"
exit 1
fi
}
#==============================================================================
# Analyze Repository
#==============================================================================
analyze_repo() {
local repo_path="$1"
local repo_name="$REPO_NAME"
[ -z "$repo_name" ] && repo_name=$(basename "$repo_path")
print_step "Analyzing repository..."
# Run the analyzer (it outputs to stderr/stdout, results go to /tmp/repo_analysis/)
"$ANALYZE_SCRIPT" "$repo_path" >&2 || true
# Find the results directory
local results_dir="/tmp/repo_analysis/results_${repo_name}"
if [ ! -d "$results_dir" ]; then
# Try without prefix
results_dir="/tmp/repo_analysis/results"
fi
if [ ! -d "$results_dir" ] || [ ! -d "$results_dir/per_language" ]; then
print_error "Could not find analysis results at $results_dir"
exit 1
fi
print_success "Analysis complete: $results_dir"
echo "$results_dir"
}
#==============================================================================
# Generate Study Materials
#==============================================================================
generate_materials() {
local analysis_dir="$1"
local output_dir="$2"
print_step "Generating study materials with offline documentation..."
# Run study materials generator
cd "$analysis_dir" || { print_error "Cannot enter $analysis_dir"; return 1; }
if "$STUDY_SCRIPT" . 2>/dev/null | grep -E "^(Created|✓|Files created)" | head -5; then
print_success "Study materials generated"
else
# Try anyway, might have succeeded
true
fi
# Create output directory and copy results
mkdir -p "$output_dir"
# Copy generated files
[ -f "documentation_links.md" ] && cp "documentation_links.md" "$output_dir/"
[ -f "anki_cards.txt" ] && cp "anki_cards.txt" "$output_dir/"
[ -f "llm_anki_prompt.md" ] && cp "llm_anki_prompt.md" "$output_dir/"
# Copy analysis data
mkdir -p "$output_dir/analysis"
[ -d "per_language" ] && cp -r "per_language" "$output_dir/analysis/"
[ -f "grep_imports.txt" ] && cp "grep_imports.txt" "$output_dir/analysis/"
[ -f "grep_keywords.txt" ] && cp "grep_keywords.txt" "$output_dir/analysis/"
[ -f "grep_function_calls.txt" ] && cp "grep_function_calls.txt" "$output_dir/analysis/"
print_success "Files saved to: $output_dir"
}
#==============================================================================
# Show Summary
#==============================================================================
show_summary() {
local output_dir="$1"
print_header "Study Materials Ready!"
echo -e "${BOLD}Output directory:${NC} $output_dir"
echo ""
echo -e "${BOLD}Generated files:${NC}"
if [ -f "$output_dir/documentation_links.md" ]; then
local doc_lines
doc_lines=$(wc -l <"$output_dir/documentation_links.md")
echo -e " 📚 ${GREEN}documentation_links.md${NC} ($doc_lines lines)"
echo " Contains links to OFFLINE documentation"
fi
if [ -f "$output_dir/anki_cards.txt" ]; then
local card_count
card_count=$(grep -c $'^\w' "$output_dir/anki_cards.txt" 2>/dev/null || echo "0")
echo -e " 🎴 ${GREEN}anki_cards.txt${NC} (~$card_count cards)"
echo " Import to Anki: File → Import → Tab separated"
fi
if [ -f "$output_dir/llm_anki_prompt.md" ]; then
echo -e " 🤖 ${GREEN}llm_anki_prompt.md${NC}"
echo " Use with ChatGPT/Claude to generate more cards"
fi
if [ -d "$output_dir/analysis" ]; then
echo -e " 📊 ${GREEN}analysis/${NC}"
echo " Raw analysis data (imports, keywords, functions per language)"
fi
echo ""
echo -e "${BOLD}Quick preview of imports with offline docs:${NC}"
if [ -f "$output_dir/documentation_links.md" ]; then
grep -A20 "import/from" "$output_dir/documentation_links.md" 2>/dev/null |
grep "^\| \`" | head -5 |
sed 's/|/│/g'
fi
echo ""
echo -e "${BOLD}Next steps:${NC}"
echo " 1. Open documentation_links.md to browse offline docs"
echo " 2. Import anki_cards.txt into Anki for spaced repetition"
echo " 3. Use llm_anki_prompt.md to generate more targeted cards"
echo ""
echo -e "${CYAN}To view a doc:${NC} xdg-open 'file:///path/from/documentation_links.md'"
}
#==============================================================================
# Main
#==============================================================================

View File

@ -0,0 +1,202 @@
#!/bin/bash
# Argument parsing and the partition/format operations.
#
# Sourced by format_sd_card.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode and
# the helper functions and variables defined above the source line.
parse_args() {
DEVICE=""
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run)
DRY_RUN=true
shift
;;
--fs)
if [[ $# -lt 2 ]]; then
echo "Missing value for --fs" >&2
exit 1
fi
FILESYSTEM="$2"
shift 2
;;
--dumbphone)
# Force settings that are friendlier to older phones:
# * MBR (dos) partition table
# * Single ~30GiB FAT32 partition
# * Leave remaining space unused
DUMBPHONE_MODE=true
FILESYSTEM="vfat"
shift
;;
-h | --help)
usage
exit 0
;;
/dev/*)
DEVICE="$1"
shift
;;
*)
echo "Unknown argument: $1" >&2
usage
exit 1
;;
esac
done
export DEVICE FILESYSTEM DRY_RUN DUMBPHONE_MODE
}
detect_sd_card() {
# List removable disks (RM=1, TYPE=disk)
# Columns: NAME, RM, SIZE, MODEL, TRAN, TYPE
local output
output=$(lsblk -o NAME,RM,SIZE,MODEL,TRAN,TYPE -nr | awk '$2==1 && $6=="disk"') || true
if [[ -z $output ]]; then
echo "No removable disks detected. Please provide device explicitly (e.g., /dev/sda)." >&2
exit 1
fi
mapfile -t candidates < <(echo "$output")
if [[ ${#candidates[@]} -eq 1 ]]; then
local name size model tran
read -r name _ size model tran _ <<< "${candidates[0]}"
DEVICE="/dev/${name}"
log "Detected removable disk: $DEVICE (${size} ${model} ${tran})"
else
echo "Multiple removable disks detected:" >&2
local i=1
for line in "${candidates[@]}"; do
local name size model tran
read -r name _ size model tran _ <<< "$line"
printf ' %d) /dev/%s %s %s %s\n' "$i" "$name" "$size" "$model" "$tran"
((i++))
done
while true; do
read -r -p "Select device to format (1-${#candidates[@]}): " choice
if [[ $choice =~ ^[0-9]+$ ]] && ((choice >= 1 && choice <= ${#candidates[@]})); then
local sel="${candidates[choice - 1]}"
local name size model tran
read -r name _ size model tran _ <<< "$sel"
DEVICE="/dev/${name}"
log "Selected device: $DEVICE (${size} ${model} ${tran})"
break
else
echo "Invalid choice." >&2
fi
done
fi
}
validate_device() {
if [[ -z ${DEVICE:-} ]]; then
detect_sd_card
fi
if [[ ! -b $DEVICE ]]; then
echo "Device $DEVICE does not exist or is not a block device." >&2
exit 1
fi
# Extra safety: refuse clearly system disks by checking if rootfs lives there
local root_dev
root_dev=$(findmnt -no SOURCE / || true)
if [[ $root_dev == "$DEVICE"* ]]; then
echo "Refusing to operate on $DEVICE because it appears to contain the root filesystem ($root_dev)." >&2
exit 1
fi
}
unmount_partitions() {
local dev base part
dev="$DEVICE"
base="${dev##*/}"
mapfile -t parts < <(lsblk -nr -o NAME,MOUNTPOINT "/dev/${base}" | awk 'NF==2 {print $1" "$2}') || true
for entry in "${parts[@]:-}"; do
read -r part mp <<< "$entry"
if [[ -n $mp ]]; then
run "umount \"$mp\""
fi
done
}
wipe_and_partition() {
local dev="$DEVICE"
if ! confirm "About to WIPE ALL DATA on $dev and create a new ${FILESYSTEM} filesystem. Continue?"; then
echo "Aborted by user." >&2
exit 1
fi
# Zap existing partition table
run "wipefs -a \"$dev\""
# Create a new partition table + partition layout
# Using sfdisk for non-interactive, reproducible layout
local sfdisk_input
if [[ $DUMBPHONE_MODE == true ]]; then
# Old phones often:
# * only support MBR (dos)
# * only support SD/SDHC (<=32GiB)
# We create an MBR table and a single ~30GiB FAT32 partition, leaving the rest unused.
# 30GiB ≈ 30 * 2^30 / 512 ≈ 62914560 sectors; start at 2048 for alignment.
sfdisk_input=$'label: dos\n2048,62914560,c,*\n'
if [[ $DRY_RUN == true ]]; then
log "DRY RUN: echo -e '$sfdisk_input' | sfdisk $dev"
else
log "RUN: create MBR (dos) with ~30GiB FAT32 partition on $dev"
echo -e "$sfdisk_input" | sfdisk "$dev"
fi
else
# Default: GPT with one partition spanning the whole device
sfdisk_input=$'label: gpt\n,;\n'
if [[ $DRY_RUN == true ]]; then
log "DRY RUN: echo -e '$sfdisk_input' | sfdisk $dev"
else
log "RUN: create GPT with one partition on $dev"
echo -e "$sfdisk_input" | sfdisk "$dev"
fi
fi
# Let the kernel re-read the partition table
sleep 2
}
format_filesystem() {
local dev base part
dev="$DEVICE"
base="${dev##*/}"
part="/dev/${base}1"
if [[ ! -b $part ]]; then
echo "Expected partition $part not found after partitioning." >&2
exit 1
fi
case "$FILESYSTEM" in
exfat)
run mkfs.exfat -n SDCARD "$part"
;;
vfat | fat32)
run mkfs.vfat -F32 -n SDCARD "$part"
;;
ext4)
run mkfs.ext4 -F -L SDCARD "$part"
;;
*)
echo "Unsupported filesystem type: $FILESYSTEM" >&2
exit 1
;;
esac
log "Formatting completed on $part with filesystem $FILESYSTEM."
}

View File

@ -103,214 +103,9 @@ EOF
exit 0
}
#==============================================================================
# Check Dependencies
#==============================================================================
check_dependencies() {
local missing=()
# shellcheck source=lib/repo_study_steps.sh
source "$SCRIPT_DIR/lib/repo_study_steps.sh"
# Check for required scripts
if [ ! -x "$ANALYZE_SCRIPT" ]; then
missing+=("analyze_repo.sh not found at $ANALYZE_SCRIPT")
fi
if [ ! -x "$STUDY_SCRIPT" ]; then
missing+=("generate_study_materials.sh not found at $STUDY_SCRIPT")
fi
# Check for basic tools
for cmd in git curl grep sed awk; do
if ! command -v "$cmd" &>/dev/null; then
missing+=("$cmd")
fi
done
if [ ${#missing[@]} -gt 0 ]; then
print_error "Missing dependencies:"
for dep in "${missing[@]}"; do
echo " - $dep"
done
exit 1
fi
}
#==============================================================================
# Ensure Offline Docs are Available
#==============================================================================
ensure_offline_docs() {
local docs_dir="$HOME/.local/share/offline-docs"
if [ ! -d "$docs_dir/python" ]; then
print_info "Offline docs not found. Setting up Python documentation..."
if [ -x "$SETUP_DOCS_SCRIPT" ]; then
"$SETUP_DOCS_SCRIPT" --python
else
print_info "Run setup_offline_docs.sh --all to enable offline documentation"
fi
fi
}
# Global to store repo name for cloned repos
REPO_NAME=""
#==============================================================================
# Get Repository
#==============================================================================
get_repo() {
local input="$1"
local repo_dir=""
# Check if it's a URL (git clone needed)
if [[ $input =~ ^https?:// ]] || [[ $input =~ ^git@ ]]; then
print_step "Cloning repository..."
# Extract repo name from URL
REPO_NAME=$(basename "$input" .git)
repo_dir="$WORK_DIR/$REPO_NAME"
mkdir -p "$WORK_DIR"
if git clone --depth 1 "$input" "$repo_dir" >&2 2>&1; then
print_success "Cloned: $input"
else
print_error "Failed to clone repository"
exit 1
fi
echo "$repo_dir"
# Local path
elif [ -d "$input" ]; then
# Convert to absolute path
repo_dir="$(cd "$input" && pwd)"
REPO_NAME=$(basename "$repo_dir")
print_success "Using local repository: $repo_dir"
echo "$repo_dir"
else
print_error "Invalid input: '$input' is not a valid URL or directory"
exit 1
fi
}
#==============================================================================
# Analyze Repository
#==============================================================================
analyze_repo() {
local repo_path="$1"
local repo_name="$REPO_NAME"
[ -z "$repo_name" ] && repo_name=$(basename "$repo_path")
print_step "Analyzing repository..."
# Run the analyzer (it outputs to stderr/stdout, results go to /tmp/repo_analysis/)
"$ANALYZE_SCRIPT" "$repo_path" >&2 || true
# Find the results directory
local results_dir="/tmp/repo_analysis/results_${repo_name}"
if [ ! -d "$results_dir" ]; then
# Try without prefix
results_dir="/tmp/repo_analysis/results"
fi
if [ ! -d "$results_dir" ] || [ ! -d "$results_dir/per_language" ]; then
print_error "Could not find analysis results at $results_dir"
exit 1
fi
print_success "Analysis complete: $results_dir"
echo "$results_dir"
}
#==============================================================================
# Generate Study Materials
#==============================================================================
generate_materials() {
local analysis_dir="$1"
local output_dir="$2"
print_step "Generating study materials with offline documentation..."
# Run study materials generator
cd "$analysis_dir"
if "$STUDY_SCRIPT" . 2>/dev/null | grep -E "^(Created|✓|Files created)" | head -5; then
print_success "Study materials generated"
else
# Try anyway, might have succeeded
true
fi
# Create output directory and copy results
mkdir -p "$output_dir"
# Copy generated files
[ -f "documentation_links.md" ] && cp "documentation_links.md" "$output_dir/"
[ -f "anki_cards.txt" ] && cp "anki_cards.txt" "$output_dir/"
[ -f "llm_anki_prompt.md" ] && cp "llm_anki_prompt.md" "$output_dir/"
# Copy analysis data
mkdir -p "$output_dir/analysis"
[ -d "per_language" ] && cp -r "per_language" "$output_dir/analysis/"
[ -f "grep_imports.txt" ] && cp "grep_imports.txt" "$output_dir/analysis/"
[ -f "grep_keywords.txt" ] && cp "grep_keywords.txt" "$output_dir/analysis/"
[ -f "grep_function_calls.txt" ] && cp "grep_function_calls.txt" "$output_dir/analysis/"
print_success "Files saved to: $output_dir"
}
#==============================================================================
# Show Summary
#==============================================================================
show_summary() {
local output_dir="$1"
print_header "Study Materials Ready!"
echo -e "${BOLD}Output directory:${NC} $output_dir"
echo ""
echo -e "${BOLD}Generated files:${NC}"
if [ -f "$output_dir/documentation_links.md" ]; then
local doc_lines
doc_lines=$(wc -l <"$output_dir/documentation_links.md")
echo -e " 📚 ${GREEN}documentation_links.md${NC} ($doc_lines lines)"
echo " Contains links to OFFLINE documentation"
fi
if [ -f "$output_dir/anki_cards.txt" ]; then
local card_count
card_count=$(grep -c $'^\w' "$output_dir/anki_cards.txt" 2>/dev/null || echo "0")
echo -e " 🎴 ${GREEN}anki_cards.txt${NC} (~$card_count cards)"
echo " Import to Anki: File → Import → Tab separated"
fi
if [ -f "$output_dir/llm_anki_prompt.md" ]; then
echo -e " 🤖 ${GREEN}llm_anki_prompt.md${NC}"
echo " Use with ChatGPT/Claude to generate more cards"
fi
if [ -d "$output_dir/analysis" ]; then
echo -e " 📊 ${GREEN}analysis/${NC}"
echo " Raw analysis data (imports, keywords, functions per language)"
fi
echo ""
echo -e "${BOLD}Quick preview of imports with offline docs:${NC}"
if [ -f "$output_dir/documentation_links.md" ]; then
grep -A20 "import/from" "$output_dir/documentation_links.md" 2>/dev/null |
grep "^\| \`" | head -5 |
sed 's/|/│/g'
fi
echo ""
echo -e "${BOLD}Next steps:${NC}"
echo " 1. Open documentation_links.md to browse offline docs"
echo " 2. Import anki_cards.txt into Anki for spaced repetition"
echo " 3. Use llm_anki_prompt.md to generate more targeted cards"
echo ""
echo -e "${CYAN}To view a doc:${NC} xdg-open 'file:///path/from/documentation_links.md'"
}
#==============================================================================
# Main
#==============================================================================
main() {
# Handle help
if [ $# -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then

View File

@ -140,118 +140,9 @@ disable_tty_idle() {
# is connected. Empty when no inhibitor is active.
inhibit_pid=""
start_idle_inhibit() {
# Hold one systemd idle inhibitor for the whole time a controller is
# connected. This replaces the previous per-event fork storm (4 xset + an
# xdotool + a dd read + a sleep on *every* joystick event, ~21 forks/s while
# gaming): a single long-lived process keeps logind from treating the session
# as idle (so it won't auto-suspend or lock), while X11 blanking stays off
# thanks to the one-shot disable_x11_idle above. Idempotent — a live inhibitor
# is reused.
if [[ -n $inhibit_pid ]] && kill -0 "$inhibit_pid" 2> /dev/null; then
return 0
fi
# NOTE: --what=idle only (NOT idle:sleep). An idle inhibitor already stops
# logind's idle-triggered auto-suspend/lock — which is all gaming needs — but
# a *sleep* inhibitor would also block *deliberate* suspend/hibernate, e.g.
# the scheduled digital-wellbeing day-specific-shutdown hibernate. Blocking
# sleep here once silently kept the PC running past every shutdown window.
systemd-inhibit --what=idle --who="idle-off" \
--why="game controller connected" sleep infinity &
inhibit_pid=$!
log "Holding idle inhibitor (pid ${inhibit_pid}) while a controller is connected"
}
stop_idle_inhibit() {
if [[ -z $inhibit_pid ]]; then
return 0
fi
kill "$inhibit_pid" 2> /dev/null || true
wait "$inhibit_pid" 2> /dev/null || true
inhibit_pid=""
log "Released idle inhibitor; normal idle behaviour resumes"
}
controller_connected() {
# Pure-bash glob check — zero forks. True if any /dev/input/js* node exists.
local dev
for dev in /dev/input/js*; do
[[ -e $dev ]] && return 0
done
return 1
}
sync_inhibit_to_controllers() {
# Hold the inhibitor exactly when a controller is present.
if controller_connected; then
start_idle_inhibit
else
stop_idle_inhibit
fi
}
start_controller_watchers() {
# Event-driven and fork-free in the hot path: react only to input-device
# add/remove (rare udev events), never to individual joystick *input* events,
# and hold a single systemd-inhibit lock while a controller is present.
if ! has_cmd systemd-inhibit; then
warn "systemd-inhibit not found; cannot hold an idle inhibitor"
return 0
fi
# EXIT covers every termination path (including a SIGTERM that interrupts the
# blocking read below); INT/TERM additionally give a clean exit status.
trap 'stop_idle_inhibit' EXIT
trap 'exit 0' INT TERM
sync_inhibit_to_controllers # apply current state once at startup
if has_cmd udevadm; then
log "Watching controller hotplug via udev (no polling)"
# Process substitution (not a pipe) keeps the loop in this shell so
# inhibit_pid persists across events.
while read -r _; do
sync_inhibit_to_controllers
done < <(udevadm monitor --udev --subsystem-match=input 2> /dev/null)
else
# Fallback when udevadm is unavailable: a low-frequency presence poll. One
# sleep per 30 s cycle (~0.03 forks/s) versus the old ~21 forks/s.
warn "udevadm not found; falling back to a 30 s presence poll"
while :; do
sync_inhibit_to_controllers
sleep 30
done
fi
}
persist_with_systemd_logind() {
# Set IdleAction=ignore in /etc/systemd/logind.conf and restart logind
# Warning: restarting logind can affect user sessions (e.g., inhibit handling). Use with care.
if [[ $persist_systemd != true ]]; then
return 0
fi
if ! has_cmd sudo; then
warn "sudo not found; cannot persist systemd-logind setting"
return 0
fi
log "Persisting: setting systemd-logind IdleAction=ignore (requires sudo)"
sudo sh -c '
set -e
conf=/etc/systemd/logind.conf
if [ ! -f "$conf" ]; then
touch "$conf"
fi
# Backup once
[ -f "${conf}.bak" ] || cp -a "$conf" "${conf}.bak"
# Ensure the key exists and is set to ignore
if grep -q "^#\?IdleAction=" "$conf"; then
sed -i "s/^#\?IdleAction=.*/IdleAction=ignore/" "$conf"
else
printf "\nIdleAction=ignore\n" >> "$conf"
fi
'
log "Restarting systemd-logind to apply changes (may briefly affect session inhibitors)"
sudo systemctl restart systemd-logind || warn "Failed to restart systemd-logind"
}
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/idle_inhibit.sh
source "$SCRIPT_DIR/lib/idle_inhibit.sh"
main() {
log "Starting idle/lock disablement"
@ -267,7 +158,7 @@ main() {
disable_tty_idle
# Optional persistence
persist_with_systemd_logind
persist_with_systemd_logind "$persist_systemd"
if [[ $watch_controller == true ]]; then
# Singleton. i3 re-execs its `exec` lines on `i3-msg restart`, and a second