Compare commits

...

7 Commits

Author SHA1 Message Date
194b006453 Split fix_bluetooth.sh 720 -> 186; defer steam_compatibility.sh
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
Four libs written in one pass rather than four sequential splits, which
is what stops the libs chaining - the entry gets one source block naming
all four and no lib sources a sibling.

steam_compatibility.sh is reverted and stays at 663. Its CACHE_MAP
associative array is declared and filled in what would be the ProtonDB
lib but read by main, so that lib fails SC2034 linted alone. Third file
deferred for the same reason: shared mutable state means the seam is not
there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 19:17:05 +02:00
0b0cea706d Record the content-hash check for config-generating scripts
The stubbed run proves the functions exist, not that what they write is
unchanged. Adds the before/after hash comparison used on setup_searxng,
and the rule that a heredoc travels with the comment explaining it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 19:13:13 +02:00
d9c315e3ef Split setup_searxng.sh 912 -> 184
Six libs: the script has four phases and write_stack alone was 342 lines
because it emits three config files from heredocs. That became three
functions, one per file, each keeping the comment that explains it -
including why settings.yml is mode 640 and not 600.

For a script whose job is writing config, "the functions still exist" is
not enough. Compared the sorted non-comment lines of the original
write_stack against its three successors: identical hash, so every line
of emitted compose, settings.yml and limiter.toml is byte-for-byte the
same and only the wrappers were added.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 19:11:40 +02:00
b84ad9d971 Update the handoff: 118 left, three shell files deferred with reasons
Also records that the pre-commit shellcheck hook lints each lib in
isolation - stricter than shellcheck -x on the entry, and the check that
decides whether a seam is real - and corrects the old advice to repeat
set -euo pipefail in every lib.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 19:08:17 +02:00
2527fb37e6 Split three large linux_configuration scripts, defer a fourth
organize_downloads.sh 513 -> 72, setup_kcd2_dice_solver.sh 497 -> 112,
fix_ubuntu_performance.sh 494 -> 150. First 490+ line scripts done; all
three needed two or three seams.

Repeated splitting chained the libs - each sourced the next, because the
tool inserts its source line relative to the file it just wrote.
Flattened so the entry sources all three and no lib sources a sibling.

diagnose_pacman_hook_stall.sh is reverted and stays at 493. Its
transaction runner assigns LAST_ELAPSED that the caller reads and reads
PACMAN_BIN that the caller defines, so linted alone it is SC2034 plus
SC2153. The pre-commit hook lints each lib in isolation and fails, while
shellcheck -x on the entry passes - suppressing that would be papering
over a seam that does not exist.

organize_downloads.sh is the ExecStart of media-organizer.service; the
unit still resolves and the script still parses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 19:06:16 +02:00
4ac8c77abd Update the handoff: 121 left, linux_configuration 84 -> 63
Records the six shell batches, the two files deliberately left over the
cap with their reasons, and points at the verifier script rather than
describing the check in prose.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 19:01:22 +02:00
dbc4d099a3 Commit the shell-split verifier and the traps it found
meta/scripts/verify_shell_split.sh was a scratchpad file; it has caught
five bugs across 18 splits that bash -n and shellcheck both passed on,
so it belongs in the repo. Tested in both directions - it fails on a
deliberately broken source line and passes once restored.

docs/shell-split-recipes.md gains what the last two batches taught:
splitting a file twice can displace the first cut's source line, globals
read across a seam have three different fixes depending on how many, and
unguarded cd shows up constantly because a moved function finally gets
linted on its own.

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

View File

@ -11,10 +11,13 @@ enforcement script that mutates the live system or the phone.**
- After each split, `bash -n` and `shellcheck` the entry script _and_ every new
lib. **Neither catches a `source` line that resolves to the wrong path** —
both passed clean on a split whose lib was unreachable at runtime.
- So the real check is a **stubbed run**: copy the entry script and its libs to
a `mktemp -d`, `sed` the final `main` invocation into a `declare -F` probe,
and run it. That executes the `source` lines and nothing else. This caught
the bug below; no static check did.
- So the real check is a **stubbed run**, scripted as
`meta/scripts/verify_shell_split.sh <script> <function>...`: it mirrors the
repo tree into a `mktemp -d`, replaces the final `main` invocation with a
`declare -F` probe, and runs that. The `source` lines execute and nothing
else, which makes it safe for installers. Across 18 splits it caught five
bugs no static check did. It needs the script to end in `main "$@"`; for the
rest, use the by-hand checks below.
### Use `${BASH_SOURCE[0]}`, not `$0`
@ -95,6 +98,59 @@ grep -rn -E '^\s*(sudo )?(install|cp)\s.*(SCRIPT_DIR|REPO).*/usr/local/' \
Reuse it instead of adding a second declaration, or the script dies with
`readonly variable`. `bash -n` and `shellcheck` both pass on that.
### Splitting the same file twice is the risky move
The splitter inserts its `source` line relative to the file as it currently
stands, so a second pass can **displace the first pass's line**. On
`20-dump-stock.sh` that left `verify_dump` called but never defined, and the
repair then put the line inside the lib rather than the entry script.
After any double split: `grep -n 'source "\$SCRIPT_DIR' <entry> <libs>` and
check that the entry sources **every** lib and **no lib sources another**.
`shellcheck` without `-x` on a lib is what surfaces this — a lib sourcing a
sibling reports SC1091 "does not exist", because the relative path is only
valid from the entry script's directory.
### Globals read across the seam
Common, and the fix depends on how many:
- **One or two, module-level constants** — rename to UPPERCASE, matching what
the surrounding files already do (`QUIET`, `FORCE`). Worked for
`DESKTOP_DIR` in `fix_unity.sh`.
- **A flag the caller computes** — pass it as a parameter. Worked for
`persist_with_systemd_logind`.
- **Several, threaded through three files** — stop. See below.
### Unguarded `cd` turns up constantly
Two found in five splits (`build_website`, the study-material generator), both
pre-existing, both a real bug: a failed `cd` runs the next command in the
caller's directory. They only surface on splitting because a moved function
gets linted in isolation. Fix with `|| die` / `|| return 1`, never a suppression.
### Scripts that generate config need a content check
For a setup script, "the functions still exist" is the wrong question — what
matters is that the compose file, unit or settings file it writes is unchanged.
The stubbed run cannot tell you that. Compare the moved region before and
after, ignoring comments and ordering:
```bash
git show HEAD:<script> | awk '/^the_func\(\) \{/,/^\}$/' \
| grep -vE '^\s*(#|$)' | sort | md5sum
cat <the new libs> | grep -vE '^\s*(#|$)' \
| grep -v '^new_func_name\|^}' | sort | md5sum
```
Equal hashes mean every emitted line survived and only wrappers were added.
Used on `setup_searxng.sh`, whose `write_stack` was 342 lines of heredoc
emitting three files.
**Keep each heredoc with the comment that explains it.** `setup_searxng.sh`
records why `settings.yml` is mode 640 and not 600 (at 600 the granian worker
dies with EACCES) — that comment is worth more than the code around it.
### When to give up on a seam
`clean_audio.sh` was reverted. Two probe-result globals were read by functions

View File

@ -0,0 +1,19 @@
{
"title": "Split three large linux_configuration scripts, deferring a fourth",
"objective": "Bring organize_downloads.sh (513), setup_kcd2_dice_solver.sh (497) and fix_ubuntu_performance.sh (494) under the 250-line cap, and establish that a seam sharing mutable state with its caller must be abandoned rather than suppressed.",
"acceptance_criteria": [
"All three entry scripts and all seven new libs are at most 250 lines.",
"The pre-commit shellcheck hook passes on every touched file, with no new suppression and no disable directive. That hook lints each lib in isolation, which is stricter than shellcheck -x on the entry script.",
"No lib sources a sibling: the entry script sources every lib directly.",
"The stubbed run reports every moved function as defined, for all three scripts.",
"organize_downloads.sh is the ExecStart of the live media-organizer.service unit, so after the split that path must still resolve and the script must still parse.",
"No script is executed. These move files in ~/Downloads, write compose stacks and change sysctl and systemd settings.",
"diagnose_pacman_hook_stall.sh is fully restored to 493 lines, leaving no partial split behind."
],
"out_of_scope": [
"Executing any organize, setup or fix step.",
"diagnose_pacman_hook_stall.sh, whose load generator assigns LAST_ELAPSED read by the caller and reads PACMAN_BIN defined by it; splitting it would need a suppression.",
"Changing what any script does when run."
],
"verifier": "meta/scripts/verify_shell_split.sh per script, plus pre-commit run shellcheck over all touched files, plus systemctl cat media-organizer and test -f on its ExecStart, plus check_file_length.sh and the real git commit for jscpd."
}

View File

@ -0,0 +1,18 @@
{
"title": "Split fix_bluetooth.sh under the cap, deferring steam_compatibility.sh",
"objective": "Bring fix_bluetooth.sh (720 lines) under the 250-line cap using a single multi-lib pass, and confirm that a seam crossing shared mutable state must be abandoned rather than suppressed.",
"acceptance_criteria": [
"The entry script and all four new libs are at most 250 lines.",
"The pre-commit shellcheck hook passes on every touched file, with no new suppression and no disable directive.",
"All four libs are written in one pass, so the entry script sources every lib directly and no lib sources a sibling.",
"The stubbed run reports every moved function as defined.",
"No script is executed. fix_bluetooth.sh reloads btusb and restarts bluetooth and PipeWire, which would drop live audio.",
"steam_compatibility.sh is fully restored to 663 lines, with the unrelated libs already present in the same lib/ directory left untouched."
],
"out_of_scope": [
"Executing any bluetooth or audio fix.",
"steam_compatibility.sh, whose CACHE_MAP associative array is written in one prospective lib and read by main.",
"Changing what any script does when run."
],
"verifier": "meta/scripts/verify_shell_split.sh, plus pre-commit run --files over all touched files, plus check_file_length.sh, plus ls of the shared lib/ directory to confirm the revert removed only what it should."
}

View File

@ -0,0 +1,19 @@
{
"title": "Split setup_searxng.sh under the 250-line cap",
"objective": "Bring linux_configuration/scripts/single_use/features/setup_searxng.sh (912 lines) under the cap, and establish the verification a split must pass when the moved code generates service configuration.",
"acceptance_criteria": [
"The entry script and all six new libs are at most 250 lines.",
"The pre-commit shellcheck hook passes on every touched file, with no new suppression and no disable directive.",
"No lib sources a sibling: the entry script sources all six directly.",
"The stubbed run reports every moved function as defined.",
"The content the script generates is byte-identical: comparing the non-comment lines of the original write_stack against the three functions it became must produce the same hash. A split that quietly altered a compose file or settings.yml would pass every other check.",
"The comment explaining why settings.yml is mode 640 rather than 600 travels with the code it explains.",
"No script is executed."
],
"out_of_scope": [
"Executing the setup, starting containers or reloading Caddy.",
"Changing anything the script writes.",
"The other very large scripts (setup_nextcloud_raspberry.sh, check_and_enable_services.sh and the rest), which are separate commits."
],
"verifier": "meta/scripts/verify_shell_split.sh, plus an md5 comparison of the sorted non-comment lines of the original write_stack against its three successor functions, plus pre-commit run --files and check_file_length.sh."
}

View File

@ -0,0 +1,51 @@
{
"intent": "Split three of the largest remaining linux_configuration scripts, and defer a fourth whose seam cannot be made lint-clean without a suppression.",
"scope": [
"single_use/utils/organize_downloads.sh (513 -> 72) + lib/download_classify.sh, download_sizes.sh, download_media.sh",
"single_use/features/setup_kcd2_dice_solver.sh (497 -> 112) + lib/kcd2_serve.sh, kcd2_expose.sh, kcd2_autorebuild.sh",
"single_use/fixes/fix_ubuntu_performance.sh (494 -> 150) + lib/ubuntu_perf_fixes.sh, ubuntu_perf_more.sh",
"Deferred and fully restored: single_use/fixes/diagnose_pacman_hook_stall.sh (493)",
"Non-goal: no script executed"
],
"changes": [
"Three cuts each for organize_downloads.sh and setup_kcd2_dice_solver.sh, two for fix_ubuntu_performance.sh. These are the first 490+ line scripts done, and every one needed more than one seam.",
"Repeated splitting chained the libs - each new lib sourced the next, because the tool inserts its source line relative to the file it just wrote. Flattened so organize_downloads.sh sources all three directly and no lib sources a sibling, and removed a leftover SCRIPT_DIR the chain had left in a lib.",
"diagnose_pacman_hook_stall.sh was reverted to HEAD. Its transaction runner assigns LAST_ELAPSED which the caller reads, and reads PACMAN_BIN which the caller defines; linted as a fragment that is SC2034 plus SC2153, and the pre-commit hook lints each lib in isolation. Neither is a real bug, which is exactly why suppressing them would be wrong - the honest answer is that this seam does not exist."
],
"verification": [
{
"command": "meta/scripts/verify_shell_split.sh per script",
"result": "fail then pass",
"evidence": "organize_downloads.sh first reported SC1091 for a lib sourcing a sibling; after flattening, all three report 'libs sourced, functions defined'."
},
{
"command": "pre-commit run shellcheck --files <all touched>",
"result": "fail then pass",
"evidence": "Failed on the pacman lib's SC2034/SC2153. This is the check that matters here and is stricter than shellcheck -x on the entry script, which passed on the same code - the hook lints each lib alone, with no view of the caller's globals. Passes now that the split is reverted."
},
{
"command": "systemctl cat media-organizer.service, test -f its ExecStart, bash -n that file",
"result": "pass",
"evidence": "Resolves to organize_downloads.sh and parses. This is one of only two units pointing into the repo, and it is the script that shrank most in this batch (513 -> 72)."
},
{
"command": "git checkout HEAD -- diagnose_pacman_hook_stall.sh, then shellcheck -x",
"result": "pass",
"evidence": "Restored to 493 lines and clean. Note the first `git checkout` without HEAD restored the staged split rather than the original - checked with wc -l, not assumed."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all",
"result": "pass",
"evidence": "None of the three entry scripts or seven libs is listed."
}
],
"risks": [
"None of the three was run. organize_downloads.sh moves files in ~/Downloads and runs from a live systemd timer; verifying it by running would be exactly the mutation decision 6 forbids. The unit-path check and bash -n are the strongest available evidence.",
"The lib-chaining bug now has two instances (20-dump-stock.sh, organize_downloads.sh). Any script split more than twice needs its source lines grepped afterwards; the tool does not do this itself.",
"diagnose_pacman_hook_stall.sh remains at 493 lines, the largest deferred file. Splitting it needs the LAST_ELAPSED/PACMAN_BIN state passed explicitly rather than shared."
],
"rollback": [
"git revert the commit; the three scripts return to their previous sizes and the seven libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored scripts."
]
}

View File

@ -0,0 +1,44 @@
{
"intent": "Split fix_bluetooth.sh (720 lines) under the cap in a single multi-lib pass, and defer steam_compatibility.sh whose seam crosses a shared associative array.",
"scope": [
"linux_configuration/scripts/single_use/fixes/fix_bluetooth.sh (720 -> 186)",
"lib/bt_adapter.sh, bt_pairing.sh, bt_audio.sh, bt_report.sh (new)",
"Deferred and fully restored: single_use/utils/steam_compatibility.sh (663)",
"Non-goal: no script executed"
],
"changes": [
"fix_bluetooth.sh split into four libs in one pass rather than four sequential passes. Writing all the libs at once is what avoids the chaining bug seen twice before: the entry gets a single source block naming every lib, and no lib sources a sibling.",
"The four libs follow the script's own phases: adapter and firmware recovery, pairing and USB autosuspend, PipeWire and audio, then instructions and diagnostics.",
"steam_compatibility.sh was reverted. Its CACHE_MAP associative array is declared and populated in what would be the ProtonDB lib but read by main, so the lib fails SC2034 when linted alone. Same class as the pacman stall script: the seam does not exist without passing that state explicitly."
],
"verification": [
{
"command": "meta/scripts/verify_shell_split.sh fix_bluetooth.sh check_firmware remove_stale_pairing check_pipewire_health show_instructions dump_diagnostics connect_device",
"result": "pass",
"evidence": "'libs sourced, functions defined' across all four libs, first try - no chaining and no SCRIPT_DIR collision."
},
{
"command": "pre-commit run --files <changed>",
"result": "pass",
"evidence": "shellcheck (which lints each lib in isolation), shfmt, the shebang hook and jscpd all pass."
},
{
"command": "git checkout HEAD -- steam_compatibility.sh, rm its libs, shellcheck -x",
"result": "pass",
"evidence": "Restored to 663 lines and clean, with the unrelated libs in that same lib/ directory left in place - checked by listing the directory rather than assuming."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all",
"result": "pass",
"evidence": "fix_bluetooth.sh and its four libs are all under the cap; the largest is 214 lines."
}
],
"risks": [
"fix_bluetooth.sh was not run: it reloads btusb, restarts bluetooth and PipeWire, and reconnects devices. Running it would disconnect live audio, which is exactly the mutation decision 6 excludes.",
"steam_compatibility.sh joins the deferred list at 663 lines - the largest remaining single_use file. Splitting it needs CACHE_MAP passed or rebuilt rather than shared across the seam."
],
"rollback": [
"git revert the commit; fix_bluetooth.sh returns to 720 lines and the four libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored script."
]
}

View File

@ -0,0 +1,43 @@
{
"intent": "Split setup_searxng.sh (912 lines) under the cap, the first of the very large scripts, and establish how to verify a split that moves generated config content.",
"scope": [
"linux_configuration/scripts/single_use/features/setup_searxng.sh (912 -> 184)",
"lib/searxng_stack.sh, searxng_settings.sh, searxng_limiter.sh, searxng_start.sh, searxng_expose.sh, searxng_status.sh (new)",
"Non-goal: no script executed, no generated config content changed"
],
"changes": [
"Six libs rather than one or two: the script has four clear phases (write the stack, start it, expose it, report status) and write_stack alone was 342 lines because it emits three config files from heredocs.",
"write_stack became three functions, one per file written, keeping each heredoc with the comment that explains it - including the note about settings.yml needing mode 640 rather than 600, which records a real failure (the granian worker dies with EACCES at 600).",
"The entry script now sources all six libs directly; no lib sources a sibling."
],
"verification": [
{
"command": "meta/scripts/verify_shell_split.sh setup_searxng.sh write_stack write_searx_settings write_searx_limiter wait_for_site status_cmd setup_cmd ensure_firewall",
"result": "pass",
"evidence": "'libs sourced, functions defined' - all seven functions resolve across the six libs."
},
{
"command": "compare the non-comment lines of the original write_stack against the three new functions, sorted, by md5",
"result": "pass",
"evidence": "c90298c6533a64458e74e3032b5d5279 on both sides. Every line of emitted compose, settings.yml and limiter.toml content is byte-identical; the only additions are the two function wrappers and the two calls to them. This is the check that matters for a script whose whole job is writing config - the stubbed run proves the functions exist, not that what they write is unchanged."
},
{
"command": "pre-commit run --files <changed>",
"result": "pass",
"evidence": "shellcheck, shfmt, the shebang-executable hook and jscpd all pass, with six new libs in one commit."
},
{
"command": "bash ~/utils/scripts/check_file_length.sh --all",
"result": "pass",
"evidence": "None of the seven files is listed; the largest lib is 235 lines."
}
],
"risks": [
"Not executed: it writes /etc/searxng config, starts containers and reloads Caddy. The content-hash comparison is the substitute for running it, and is stronger evidence than the stubbed run for this particular script.",
"searxng_settings.sh is 235 lines, mostly one heredoc. Any addition to settings.yml pushes it over the cap, and the next seam there is not obvious - the heredoc cannot be split without changing what is written."
],
"rollback": [
"git revert the commit; setup_searxng.sh returns to 912 lines and the six libs disappear.",
"After rollback, re-run bash -n and shellcheck on the restored script."
]
}

View File

@ -0,0 +1,44 @@
{
"intent": "Commit the shell-split verifier as a repo script instead of leaving it in a scratchpad, since it has caught five bugs that bash -n and shellcheck both missed.",
"scope": [
"meta/scripts/verify_shell_split.sh (new)",
"docs/shell-split-recipes.md (points at it, and records the double-split, cross-seam-global and unguarded-cd findings)",
"Non-goal: no behaviour change to any script it checks"
],
"changes": [
"Added meta/scripts/verify_shell_split.sh. It mirrors the repo tree into a mktemp -d, copies the entry script and its lib/, replaces the final main invocation with a declare -F probe, and runs that. The source lines execute and nothing else, which is what makes it usable on installers and enforcement scripts under decision 6.",
"Its header records what it caught across 18 splits: SCRIPT_DIR computed from $0, a redeclared readonly SCRIPT_DIR, a source line displaced by a second split, and two libs sourcing a sibling. It also states its limit - the script must end in main \"$@\".",
"Resolved two SC2016 warnings by building the literal dollar sign through a variable rather than adding a disable directive, so the file is clean with no suppression.",
"docs/shell-split-recipes.md now points at the script and adds three sections earned in the last two batches: splitting a file twice, globals read across the seam, and unguarded cd."
],
"verification": [
{
"command": "bash meta/scripts/verify_shell_split.sh <a correctly split script>",
"result": "pass",
"evidence": "install_joplin.sh reports 'libs sourced, functions defined'."
},
{
"command": "deliberately point the source line at a nonexistent lib, re-run, then restore",
"result": "pass",
"evidence": "Reports 'lib/DOES_NOT_EXIST.sh: No such file or directory' and exits non-zero; passes again once restored. Tested in both directions, because a checker that never fails is worse than none."
},
{
"command": "shellcheck meta/scripts/verify_shell_split.sh",
"result": "pass",
"evidence": "Clean with no disable directive."
},
{
"command": "pre-commit run --files <changed>",
"result": "pass",
"evidence": "shellcheck, shfmt and the shebang-executable hook all pass."
}
],
"risks": [
"The verifier only works on scripts ending in `main \"$@\"` or `main`. Scripts that run top-level statements silently do less: the probe replaces nothing and the script would run for real, so those must use the by-hand checks in the doc instead. The header says so, but it is not enforced.",
"It mirrors only linux_configuration/scripts/lib and the script's own lib/. A script sourcing something outside those paths would fail in the temp tree for a reason unrelated to the split."
],
"rollback": [
"git revert the commit; the script disappears and the doc loses its pointer.",
"The scratchpad copy is session-local and not a durable fallback."
]
}

View File

@ -0,0 +1,223 @@
#!/bin/bash
# Auto-rebuild timer and unit installation for the dice solver site.
#
# Sourced by setup_kcd2_dice_solver.sh; split out to keep kcd2_expose.sh
# under the 250-line cap. Sourced rather than run, so it inherits the
# caller's strict mode and the variables above the source line.
# --- Phase 7: auto-rebuild on commit ----------------------------------------
# The build runs in a memory-capped systemd user unit rather than inside the
# git hook. MemorySwapMax=0 is required, not cosmetic: this box has ~4 GB of
# zram (swap held IN ram), so a memory-limited cgroup without it thrashes zram
# instead of dying cleanly, and freezes the machine. A git hook running tsc and
# vite is precisely the scenario that costs.
install_autorebuild() {
ensure_dir "$UNIT_DIR"
cat >"$UNIT_FILE" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
[Unit]
Description=Rebuild the KCD2 dice solver static bundle
[Service]
Type=oneshot
WorkingDirectory=${DICE_SRC}
ExecStart=${DICE_BUILD}
MemoryMax=3G
MemorySwapMax=0
EOF
systemctl --user daemon-reload
log_ok "Installed ${UNIT_FILE}."
[[ -d "${REPO_ROOT}/.git" ]] || die "${REPO_ROOT} is not a git repository."
cat >"$HOOK_FILE" <<EOF
#!/bin/bash
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
# Republishes https://${DICE_DOMAIN}/ when main gains solver changes.
[[ "\$(git rev-parse --abbrev-ref HEAD)" == main ]] || exit 0
git diff --name-only HEAD~1 HEAD -- kcd2_dice_solver/ | grep -q . || exit 0
# --no-block so the commit is never slowed, || true so systemd can never fail it.
systemctl --user start --no-block ${UNIT_NAME} || true
EOF
chmod +x "$HOOK_FILE"
log_ok "Installed ${HOOK_FILE}."
}
# --- Phase 8: firewall ------------------------------------------------------
# setup_wireguard_ssh.sh owns /etc/nftables.conf and regenerates it from
# scratch — `flush ruleset` and all — on every run. That is fine on a quiet
# machine and rude on a busy one: it momentarily drops the whole ruleset while
# games, VPN links and long-lived connections are relying on it. Since the only
# thing this deployment needs is 80/443 already being accepted, check first and
# only pay for the regeneration when the rule is genuinely missing.
# Exact token membership rather than a regex over the rule text: a loose
# pattern would also match "8080, 4433" and wrongly conclude the ports are open.
web_ports_open() {
local line ports
while read -r line; do
# Strip everything but digits and commas, then test for whole tokens.
ports=",${line//[^0-9,]/},"
if [[ $ports == *,80,* && $ports == *,443,* ]]; then
return 0
fi
done < <(sudo -n nft list ruleset 2>/dev/null | grep -oE 'tcp dport \{[^}]*\}')
return 1
}
ensure_firewall() {
if web_ports_open; then
log_ok "Ports 80/443 already accepted — leaving the ruleset untouched."
return 0
fi
log_info "Opening ports 80/443 via setup_wireguard_ssh.sh…"
sudo bash "$WG_SCRIPT" allow-web
}
# --- Phase 9: report --------------------------------------------------------
print_report() {
cat <<EOF
============================================================================
KCD2 dice solver deployed.
============================================================================
Solver : https://${DICE_DOMAIN}/
Auto-rebuild: committing to main with changes under kcd2_dice_solver/ starts
${UNIT_NAME}, which rebuilds dist/ in place.
Watch it: journalctl --user -u ${UNIT_NAME} -f
Force it: systemctl --user start ${UNIT_NAME}
NOTE: the rebuild builds the WORKING TREE, not the commit. An unrelated
uncommitted edit that happens to be present when it runs will ship to the live
site. Commit or set aside unrelated work before triggering a rebuild.
Acceptance test (do this on your phone):
Turn Wi-Fi OFF (use cellular) and open https://${DICE_DOMAIN}/ —
all 43 dice should be on one screen and tappable.
============================================================================
EOF
}
setup_cmd() {
print_setup_header "KCD2 dice solver setup"
preflight
build_solver
write_serve_stack
# The snippet goes into the SHARED sites/ directory, so it is written only
# after the backend is up and verified. Writing it first means a failure in
# start_site leaves an orphan behind that the next `caddy reload` from any
# other service picks up — the edge then serves this domain as a 502 and
# starts ACME retries for a host with no backend.
start_site
write_snippet
reload_caddy
install_autorebuild
ensure_firewall
print_report
log_ok "KCD2 dice solver 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 with a non-empty body, else 1.
# The body-size check matters: a host-matcher misconfiguration answers 200
# with nothing in it, which a status-only check would call healthy.
#
# Certificates are NOT skipped for https URLs — `curl -k` would report an
# expired or failed-ACME cert as a healthy site, which is precisely the kind
# of green-while-broken this command exists to catch. The loopback check runs
# over plain http, so it needs no exception.
local url="$1" out code size
out="$(curl -s -o /dev/null -w '%{http_code} %{size_download}' --max-time 10 \
${2:+-H "Host: $2"} "$url" 2>/dev/null || echo "000 0")"
read -r code size <<<"$out"
[[ $code == "200" && ${size:-0} -gt 0 ]] && echo 0 || echo 1
}
status_cmd() {
print_setup_header "KCD2 dice solver 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 "${DICE_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 "$DICE_CONTAINER"; then
status_line 0 "${DICE_CONTAINER} container running"
local pid listeners
pid="$(docker inspect -f '{{.State.Pid}}' "$DICE_CONTAINER" 2>/dev/null || echo "")"
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
if grep -qE ':(80|443)\b' <<<"$listeners"; then
status_line 1 "${DICE_CONTAINER} is CONTENDING for :80/:443 with ${CADDY_CONTAINER}"
else
status_line 0 "${DICE_CONTAINER} listens only on ${DICE_PORT}"
fi
else
status_line 1 "${DICE_CONTAINER} container not running"
fi
status_line "$(check_http "http://127.0.0.1:${DICE_PORT}/" "$DICE_DOMAIN")" \
"local static server (127.0.0.1:${DICE_PORT}, Host: ${DICE_DOMAIN})"
if [[ -f $DICE_SNIPPET ]]; then
status_line 0 "Caddy snippet present"
else
status_line 1 "Caddy snippet missing"
fi
if getent hosts "$DICE_DOMAIN" >/dev/null; then
status_line 0 "${DICE_DOMAIN} resolves"
else
status_line 1 "${DICE_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${DICE_DOMAIN}/")" \
"external https://${DICE_DOMAIN}/"
# The hook lives in .git/hooks, which is not version-controlled, so it is
# lost on a fresh clone and must be checked rather than assumed. Spelled as
# an explicit if: with two conditions, A && B || C really would misfire.
if [[ -x $HOOK_FILE ]] && grep -q "$UNIT_NAME" "$HOOK_FILE" 2>/dev/null; then
status_line 0 "post-commit auto-rebuild hook installed"
else
status_line 1 "post-commit hook missing — re-run setup"
fi
if [[ -f $UNIT_FILE ]]; then
status_line 0 "${UNIT_NAME} installed"
else
status_line 1 "${UNIT_NAME} missing — re-run setup"
fi
if systemctl --user is-failed --quiet "$UNIT_NAME"; then
status_line 1 "last auto-rebuild FAILED — journalctl --user -u ${UNIT_NAME}"
else
status_line 0 "no failed auto-rebuild recorded"
fi
# "not failed" also covers "never ran", so check the artefact rather than the
# unit: if any source file is newer than the published bundle, the hook is
# not firing and the site is quietly serving an old build.
local newest_src
newest_src="$(find "${DICE_SRC}/src" "${DICE_SRC}/index.html" -type f -newer \
"${DICE_SRC}/dist/index.html" -print -quit 2>/dev/null || true)"
if [[ -n $newest_src ]]; then
status_line 1 "published bundle is STALE (e.g. ${newest_src#"${DICE_SRC}/"}) — run: systemctl --user start ${UNIT_NAME}"
else
status_line 0 "published bundle is up to date with src/"
fi
}

View File

@ -0,0 +1,60 @@
#!/bin/bash
# Edge-conflict checks, site startup and Caddy reload.
#
# Sourced by setup_kcd2_dice_solver.sh; split out to keep kcd2_serve.sh
# under the 250-line cap. Sourced rather than run, so it inherits the
# caller's strict mode and the variables above the source line.
# This container shares the host network namespace with the public edge, so a
# misconfiguration here does not fail locally — it quietly steals a share of
# :80 or :443 from every other site on the box. Gate on it rather than trust
# the config to stay correct.
assert_no_edge_conflict() {
local pid listeners
pid="$(docker inspect -f '{{.State.Pid}}' "$DICE_CONTAINER" 2>/dev/null || echo "")"
[[ -n $pid && $pid != "0" ]] || die "Could not read the ${DICE_CONTAINER} PID."
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
# Demand positive evidence FIRST. Asserting only the absence of :80/:443
# fails open: if `ss` returns nothing — a stale PID after a restart, or
# sudo -n unavailable — every "is it bad?" test misses and the guard happily
# reports success without having looked at anything.
if ! grep -qE '(^|[[:space:]])127\.0\.0\.1:'"${DICE_PORT}"'([[:space:]]|$)' <<<"$listeners"; then
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "Could not confirm ${DICE_CONTAINER} listens on 127.0.0.1:${DICE_PORT}. Container stopped."
fi
if grep -qE ':(80|443)\b' <<<"$listeners"; then
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "${DICE_CONTAINER} bound :80/:443 — it would contend with ${CADDY_CONTAINER}. Container stopped."
fi
# Must be on loopback, not 0.0.0.0/*: host networking would otherwise expose
# the unfronted static server to the whole LAN.
if grep -qE '(\*|0\.0\.0\.0):'"${DICE_PORT}"'\b' <<<"$listeners"; then
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "${DICE_CONTAINER} bound ${DICE_PORT} on all interfaces, not loopback. Container stopped."
fi
log_ok "${DICE_CONTAINER} listens on loopback:${DICE_PORT} only — no contention, not LAN-exposed."
}
start_site() {
log_info "Starting the ${DICE_CONTAINER} container…"
docker compose -f "$DICE_COMPOSE" up -d
if wait_for_site; then
log_ok "Solver answering on http://127.0.0.1:${DICE_PORT}/."
else
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "Solver did not become reachable on 127.0.0.1:${DICE_PORT} (container stopped)."
fi
assert_no_edge_conflict
}
# --- Phase 6: 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
}

View File

@ -0,0 +1,103 @@
#!/bin/bash
# Compose stack, Caddy snippet and readiness polling for the dice solver.
#
# Sourced by setup_kcd2_dice_solver.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 3: the static-serve stack ----------------------------------------
write_serve_stack() {
ensure_dir "$DICE_DATA_DIR"
cat >"$DICE_COMPOSE" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
services:
${DICE_CONTAINER}:
image: caddy:2.8
container_name: ${DICE_CONTAINER}
restart: unless-stopped
# host networking is REQUIRED, not a style choice: the nftables forward
# chain is policy drop with no accept rules, so a bridge-networked
# container has no outbound egress at all.
network_mode: host
volumes:
- ${DICE_SRC}/dist:/srv:ro
- ./Caddyfile:/etc/caddy/Caddyfile:ro
EOF
cat >"$DICE_INNER_CADDY" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
# Static file server on loopback; fronted by ${CADDY_CONTAINER} on the public
# domain.
#
# admin off is REQUIRED: this container shares the host network namespace with
# ${CADDY_CONTAINER}, so without it both would listen on the admin API (:2019)
# and a 'caddy reload' aimed at the edge could be applied here instead — which
# would make this process grab 80/443 and run its own ACME.
#
# auto_https off and the explicit http:// scheme are EQUALLY required, and this
# was found the hard way. A site address of "127.0.0.1:${DICE_PORT}" reads as a
# HOSTNAME, so Caddy turns on automatic HTTPS for it: it issues a local
# certificate, serves TLS on ${DICE_PORT} (so the plain-HTTP health check fails)
# and — the real damage — starts an HTTP->HTTPS redirect listener on :80. Under
# host networking that binds *:80 next to the edge, and SO_REUSEPORT then splits
# inbound HTTP between the two, which would intermittently break ACME
# challenges for every domain on this host.
#
# The site address is port-only and the loopback restriction is done with
# "bind". These are two different things and using the wrong one breaks in a way
# that looks like it works:
#
# A site address of "http://127.0.0.1:${DICE_PORT}" sets a host MATCHER of
# 127.0.0.1. ${CADDY_CONTAINER} forwards the original "Host:
# ${DICE_DOMAIN}" header, which then matches no route, and Caddy answers 200
# with an empty body. A local health check passes (curl sends Host:
# 127.0.0.1) while every real request serves a blank page.
#
# ":${DICE_PORT}" matches any Host, and "bind 127.0.0.1" restricts the
# listener itself — which the address never did. Without bind, host
# networking would expose this unfronted server to the whole LAN.
{
admin off
auto_https off
}
:${DICE_PORT} {
bind 127.0.0.1
root * /srv
# Single-page bundle: unknown paths should serve the app, not 404.
try_files {path} /index.html
file_server
encode gzip
}
EOF
log_ok "Wrote ${DICE_COMPOSE} and ${DICE_INNER_CADDY}."
}
# --- Phase 4: front it on the public domain ---------------------------------
write_snippet() {
cat >"$DICE_SNIPPET" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
${DICE_DOMAIN} {
reverse_proxy 127.0.0.1:${DICE_PORT}
}
EOF
log_ok "Wrote ${DICE_SNIPPET}."
}
# --- Phase 5: start ---------------------------------------------------------
# Sends the Host header the edge will actually forward, and requires a
# non-empty body. A bare "curl http://127.0.0.1:PORT/" sends Host: 127.0.0.1
# and returns an empty 200 against a host-matcher misconfiguration — it passes
# while every real request serves a blank page. Ask the question the edge asks.
wait_for_site() {
local _ size
for _ in $(seq 1 30); do
size="$(curl -s -o /dev/null -w '%{size_download}' \
-H "Host: ${DICE_DOMAIN}" "http://127.0.0.1:${DICE_PORT}/" 2>/dev/null || echo 0)"
if [[ ${size:-0} -gt 0 ]]; then
return 0
fi
sleep 1
done
return 1
}

View File

@ -0,0 +1,132 @@
#!/bin/bash
# Caddy snippet, firewall rules and the setup report.
#
# Sourced by setup_searxng.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.
# --- Phase 5: front it on the public domain ---------------------------------
# Header syntax matters and is easy to get wrong:
# Header "value" -> "set" (REPLACES any existing value) <-- what we want
# +Header "value" -> "add" (appends, yielding duplicates)
# >Header "value" -> "replace" (substring search/replace WITHIN a value —
# NOT a header setter. Using it here silently
# produced no header at all: it adapts to
# {"replace": {"": [{"search_regexp": "..."}]}}
# and matches nothing. Verified via caddy adapt.)
# This matters because SearXNG sends X-Content-Type-Options and Referrer-Policy
# itself via default_http_headers (its Referrer-Policy is `no-referrer`, which
# differs from ours), so the bare/"set" form is required to override rather than
# duplicate them.
write_snippet() {
cat >"$SEARX_SNIPPET" <<EOF
# Managed by setup_searxng.sh — do not edit by hand.
${SEARX_DOMAIN} {
header {
# Bare name = "set" = replace. Do NOT prefix with '+' (appends, causing
# duplicate headers) or '>' (substring-replace, which sets nothing).
Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'; manifest-src 'self'"
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "geolocation=(), microphone=(), camera=(), interest-cohort=()"
# No HSTS preload: duckdns.org is a public suffix, so kuhy.duckdns.org is
# the registrable domain — preloading would force HTTPS on every sibling
# subdomain and is effectively irreversible. Not needed to clear A+.
-Server
}
reverse_proxy 127.0.0.1:${SEARX_PORT} {
# SearXNG's botdetection needs the real client IP. Without this it logs
# "X-Forwarded-For nor X-Real-IP header is set!" and 429s every request,
# including the front page. Paired with trusted_proxies in limiter.toml —
# both halves are required, neither works alone.
header_up X-Forwarded-For {http.request.remote.host}
header_up X-Real-IP {http.request.remote.host}
}
}
EOF
log_ok "Wrote ${SEARX_SNIPPET}."
}
# --- Phase 6: 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
rm -f "$SEARX_SNIPPET"
die "Caddy config invalid — snippet removed, edge left untouched."
fi
}
# --- Phase 7: firewall ------------------------------------------------------
# setup_wireguard_ssh.sh owns /etc/nftables.conf and regenerates it from scratch
# — `flush ruleset` and all — on every run, momentarily dropping the whole
# ruleset. Since all this needs is 80/443 already being accepted, check first
# and only pay for the regeneration when the rule is genuinely missing.
web_ports_open() {
local line ports
while read -r line; do
# Exact token membership: a loose regex would also match "8080, 4433".
ports=",${line//[^0-9,]/},"
if [[ $ports == *,80,* && $ports == *,443,* ]]; then
return 0
fi
done < <(sudo -n nft list ruleset 2>/dev/null | grep -oE 'tcp dport \{[^}]*\}')
return 1
}
ensure_firewall() {
if web_ports_open; then
log_ok "Ports 80/443 already accepted — leaving the ruleset untouched."
return 0
fi
log_info "Opening ports 80/443 via setup_wireguard_ssh.sh…"
sudo bash "$WG_SCRIPT" allow-web
}
# --- Phase 8: report --------------------------------------------------------
print_report() {
cat <<EOF
============================================================================
SearXNG deployed.
============================================================================
Search : https://${SEARX_DOMAIN}/
JSON : https://${SEARX_DOMAIN}/search?q=test&format=json
Next, in order:
1. Header check (each must print exactly 1):
for h in content-security-policy strict-transport-security \\
x-content-type-options referrer-policy permissions-policy; do
printf '%s: ' "\$h"
curl -sI https://${SEARX_DOMAIN}/ | grep -ci "^\$h:"
done
2. Mozilla Observatory scan of ${SEARX_DOMAIN} — that scan IS the A+ grade.
3. JSON API FROM ANOTHER MACHINE (phone on cellular, not this host):
curl 'https://${SEARX_DOMAIN}/search?q=test&format=json'
A from-host curl cannot surface bot-detection rejection. If this returns
403/429, fix the limiter allowlist — do NOT disable the limiter.
Acceptance test (do this on your phone):
Turn Wi-Fi OFF (use cellular) and run a real search at https://${SEARX_DOMAIN}/
============================================================================
EOF
}
setup_cmd() {
print_setup_header "SearXNG setup"
preflight
write_stack
# The snippet goes into the SHARED sites/ directory, so it is written only
# after the backend is up and verified. Writing it first means a failure in
# start_stack leaves an orphan behind that the next `caddy reload` from any
# other service picks up — the edge then serves this domain as a 502 and
# starts ACME retries for a host with no backend.
start_stack
write_snippet
reload_caddy
ensure_firewall
print_report
log_ok "SearXNG setup complete."
}

View File

@ -0,0 +1,58 @@
#!/bin/bash
# The SearXNG limiter.toml, without which botdetection 429s everything.
#
# Sourced by setup_searxng.sh; split out to keep searxng_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.
write_searx_limiter() {
# Without this file SearXNG logs "missing config file:
# /etc/searxng/limiter.toml" and runs with no trusted_proxies, so the
# forwarded client IP is never trusted and botdetection 429s *everything*.
cat >"$SEARX_LIMITER" <<'EOF'
# Managed by setup_searxng.sh — do not edit by hand.
[botdetection]
ipv4_prefix = 32
ipv6_prefix = 48
# The edge (gitea-caddy) shares the host network namespace, so its requests
# arrive from loopback. Without 127.0.0.0/8 here the X-Forwarded-For that Caddy
# sends is ignored, every request looks like it came from the proxy itself, and
# rate limiting collapses onto a single bucket.
trusted_proxies = [
'127.0.0.0/8',
'::1',
]
[botdetection.ip_limit]
filter_link_local = false
# Off (the shipped default). link_token sends a probe the client must fetch to
# prove it renders HTML, which no scripted JSON client can satisfy. IP-based
# rate limiting below is unaffected and still applies.
link_token = false
[botdetection.ip_lists]
block_ip = []
# pass_ip bypasses ALL botdetection (including the Sec-Fetch/User-Agent probe
# headers) for these addresses.
#
# This is what makes search.formats = [html, json] usable. A scripted JSON
# client — an MCP server, a script — cannot send Sec-Fetch-Mode/Site/Dest, and
# botdetection 429s anything that lacks them, so WITHOUT this entry the JSON API
# is unreachable for every non-browser client. Verified: with browser headers a
# search returns 200 + results; the identical request without Sec-Fetch-* gets
# 429.
#
# Deliberately LOOPBACK ONLY. Requests arriving through the public edge carry
# the real client IP in X-Forwarded-For (trusted_proxies above), so they are
# still fully rate-limited — this exempts only tools running on this host.
pass_ip = [
'127.0.0.0/8',
'::1',
]
EOF
chmod 640 "$SEARX_LIMITER"
log_ok "Wrote ${SEARX_LIMITER}."
}

View File

@ -0,0 +1,235 @@
#!/bin/bash
# The SearXNG settings.yml, including why it is mode 640 and not 600.
#
# Sourced by setup_searxng.sh; split out to keep searxng_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.
write_searx_settings() {
local secret
secret="$(read_or_make_secret)"
cat >"$SEARX_SETTINGS" <<EOF
# Managed by setup_searxng.sh — do not edit by hand.
#
# "Vanilla" constraint: everything here is a SETTINGS change. No ui.static_path,
# no templates_path, no injected CSS/JS -- the shipped static files must keep
# matching upstream.
use_default_settings: true
general:
instance_name: "${SEARX_DOMAIN}"
# Keeps a public instance from advertising an admin contact to scrapers.
contact_url: false
enable_metrics: true
server:
port: ${SEARX_PORT}
bind_address: "127.0.0.1" # inert under granian; kept for correctness/clarity
secret_key: "${secret}"
limiter: true
# public_instance is deliberately NOT set. It force-enables link_token, a
# browser-proof challenge that requires the client to fetch a probe resource —
# which makes /search?format=json unusable for any scripted client (it 429s or
# 302s forever, and no limiter.toml setting can override it because the flag
# forces it on). It exists to satisfy searx.space directory norms, and this
# instance is deliberately unlisted, so it costs the JSON API for nothing.
# Rate limiting and the image proxy are kept via their own keys below.
# Required by the strict CSP: proxying images keeps them same-origin so
# img-src can stay 'self' without breaking result thumbnails.
image_proxy: true
method: "POST"
search:
safe_search: 0
autocomplete: "duckduckgo"
default_lang: "en"
# json is enabled for programmatic/MCP use. Note this interacts with the
# limiter's bot detection -- see the off-host verification step.
formats:
- html
- json
outgoing:
# Caps the tail so one dead engine cannot hold up a whole search.
request_timeout: 3.0
max_request_timeout: 6.0
pool_connections: 100
pool_maxsize: 20
enable_http2: true
valkey:
# Key is valkey.url; redis.url still parses but emits a DeprecationWarning.
url: valkey://127.0.0.1:${VALKEY_PORT}/0
ui:
static_use_hash: true
infinite_scroll: false
query_in_title: true
# Engine pruning — MEASURED on this host (5+ varied queries, /stats + the
# unresponsive_engines field), not guessed. Each entry says why.
#
# Cross-checked against this host's own /etc/hosts blocklist first: pinterest
# resolves to 0.0.0.0 here (blackholed by generate_hosts_file.sh), so it fails
# for a LOCAL reason and would have been misdiagnosed as a slow/dead upstream.
# It is disabled to stop the pointless request, not because the engine is bad.
#
# Re-check periodically with:
# curl -s 'http://127.0.0.1:${SEARX_PORT}/search?q=test&format=json' \\
# | grep -o '"unresponsive_engines":.*'
# Engine pruning, kuhy-selected 2026-08-09 from the /preferences engine table:
# every engine that was erroring (CAPTCHA / access denied / timeout / parsing
# error / crash) plus the slow tail, across all categories.
#
# Retained on purpose: google cse, wikipedia/wikidata and the specialist
# lookups (arch linux wiki, github, stackexchange, pypi, ...).
#
# IMPORTANT about general search: the merged general view is served by
# google cse ALONE, and was before this pruning too. The plain google and bing
# engines are marked "inactive: true" upstream, meaning they only run when
# explicitly invoked with a bang (!go -> 20 results, !bi -> 10, both
# verified working). So the pruning removed only engines that were already
# contributing zero results -- but it also means general search has a single
# point of failure. If google cse ever starts erroring, general search returns
# nothing until another engine is enabled or !go/!bi is used.
#
# pinterest is blackholed to 0.0.0.0 by this host's own /etc/hosts
# (generate_hosts_file.sh) -- a LOCAL failure that looks identical to a dead
# upstream. Disabled to stop the pointless request, not because the engine is bad.
#
# USE "inactive: true", NOT "disabled: true". Straight from enginelib:
# disabled -> "disable BY DEFAULT ... will allow the user to manually
# activate it in the settings" (i.e. only the default for a
# fresh visitor; anyone with an existing preferences cookie keeps
# running the engine)
# inactive -> "Remove the engine from the settings (disabled & removed)"
# The first pass used "disabled" and the pruned engines kept executing for any
# browser session that already had a preferences cookie -- yandex images was
# still throwing JSONDecodeErrors in the log minutes after being "disabled".
#
# EXCEPTION -- brave and qwant use "disabled", not "inactive", ON PURPOSE.
# They own an outgoing connection pool that sibling engines reference by name
# ("network: brave" <- brave.images/.videos/.news; "network: qwant" <- qwant
# news/images/videos). "inactive" REMOVES the definition, so the siblings'
# lookup dies at startup with KeyError: 'qwant' and the container never comes
# up. "disabled" keeps the pool defined while hiding the engine from results.
# Pool owners in this image: brave, qwant, yandex, piped, yacy -- of which only
# brave and qwant are pruned here. Check before making any of the rest inactive:
# grep -B4 'network: <name>' /usr/local/searxng/searx/settings.yml
#
# Re-check periodically:
# curl -s 'http://127.0.0.1:8090/search?q=test&format=json' | grep -o '"unresponsive_engines":.*'
engines:
# === general ===
- { name: brave, disabled: true } # too many requests
- { name: duckduckgo, inactive: true } # CAPTCHA
- { name: startpage, inactive: true } # Suspended: CAPTCHA
- { name: dogpile, inactive: true } # access denied
- { name: encyclosearch, inactive: true } # timeout
- { name: fastbot, inactive: true } # access denied
- { name: fireball, inactive: true } # access denied
- { name: quark, inactive: true } # unexpected crash
- { name: qwant, disabled: true } # CAPTCHA
- { name: sogou, inactive: true } # CAPTCHA
- { name: tusksearch, inactive: true } # HTTP error
- { name: yahoo, inactive: true } # HTTP protocol error
- { name: yep, inactive: true } # access denied
- { name: naver, inactive: true } # 1.9s
- { name: baidu, inactive: true } # 1.7s
- { name: abcnyheter, inactive: true } # 1.5s
- { name: boardreader, inactive: true } # 1.5s
- { name: crowdview, inactive: true } # 1.0s
# === images === (keeping ONLY google cse images)
- { name: dogpile images, inactive: true } # access denied
- { name: findfiles images, inactive: true } # unexpected crash
- { name: library of congress, inactive: true } # parsing error
- { name: pinterest, inactive: true } # 0.0.0.0 in /etc/hosts (local)
- { name: qwant images, inactive: true } # CAPTCHA
- { name: tusksearch images, inactive: true } # HTTP error
- { name: wikicommons.images, inactive: true } # too many requests
- { name: yandex images, inactive: true } # parsing error
- { name: quark images, inactive: true } # 2.9s
- { name: 1x, inactive: true } # 2.5s
- { name: baidu images, inactive: true } # 2.5s
- { name: picjumbo, inactive: true } # 2.4s
- { name: naver images, inactive: true } # 2.3s
- { name: sogou images, inactive: true } # 2.0s
- { name: unsplash, inactive: true } # 1.2s
- { name: duckduckgo images, inactive: true }
- { name: flickr, inactive: true } # 1.0s
- { name: bing images, inactive: true } # cut for the sub-1s images goal
- { name: deviantart, inactive: true } # cut for the sub-1s images goal
- { name: openverse, inactive: true } # cut for the sub-1s images goal
- { name: pexels, inactive: true } # cut for the sub-1s images goal
- { name: artic, inactive: true } # cut for the sub-1s images goal
- { name: devicons, inactive: true } # cut for the sub-1s images goal
- { name: lucide, inactive: true } # cut for the sub-1s images goal
- { name: wallhaven, inactive: true } # cut for the sub-1s images goal
# Not in the /preferences list kuhy sent -- these only surfaced as
# unresponsive under load, same failure pattern, so pruned with the rest.
- { name: brave.images, inactive: true } # too many requests
- { name: startpage images, inactive: true } # Suspended: CAPTCHA
# === videos ===
- { name: 360search videos, inactive: true } # unexpected crash
- { name: acfun, inactive: true } # timeout
- { name: brave.videos, inactive: true } # too many requests
- { name: dogpile videos, inactive: true } # access denied
- { name: fireball videos, inactive: true } # access denied
- { name: niconico, inactive: true } # HTTP connection error
- { name: pixabay videos, inactive: true } # timeout
- { name: tusksearch videos, inactive: true } # HTTP error
- { name: vimeo, inactive: true } # access denied
- { name: youtube, inactive: true } # HTTP connection error
- { name: naver videos, inactive: true } # 2.4s
- { name: sogou videos, inactive: true } # 2.0s
- { name: iqiyi, inactive: true } # 1.3s
- { name: rumble, inactive: true } # 1.3s
# === news ===
- { name: bing news, inactive: true } # parsing error
- { name: brave.news, inactive: true } # too many requests
- { name: dogpile news, inactive: true } # access denied
- { name: fireball news, inactive: true } # access denied
- { name: google news, inactive: true } # Suspended: CAPTCHA
- { name: startpage news, inactive: true } # Suspended: CAPTCHA
- { name: tusksearch news, inactive: true } # HTTP error
- { name: sogou wechat, inactive: true } # 1.7s
- { name: naver news, inactive: true } # 1.7s
# === music ===
- { name: radio browser, inactive: true } # HTTP error
- { name: yandex music, inactive: true } # HTTP error
# === it ===
- { name: codeberg, inactive: true } # timeout
- { name: metacpan, inactive: true } # HTTP error
- { name: nixos wiki, inactive: true } # timeout
- { name: baidu kaifa, inactive: true } # 2.0s
- { name: gitea.com, inactive: true } # 1.8s
- { name: rubygems, inactive: true } # 1.1s
# === science ===
- { name: openairepublications, inactive: true } # 2.7s
- { name: openairedatasets, inactive: true } # 2.7s
# === files ===
- { name: 1337x, inactive: true } # HTTP connection error
- { name: btdigg, inactive: true } # 1.5s
- { name: findfiles, inactive: true } # 1.2s
- { name: kickass, inactive: true } # HTTP connection error (surfaced under load)
# === social media ===
- { name: 9gag, inactive: true } # access denied
- { name: tootfinder, inactive: true } # access denied
EOF
# 640, NOT 600. The entrypoint chowns this file to the container's searxng
# user (uid 977), but granian's worker runs as a different uid and only has
# GROUP access — mode 600 makes it unreadable and the worker dies with
# "[Errno 13] Permission denied: /etc/searxng/settings.yml". It still is not
# world-readable, so secret_key stays protected.
chmod 640 "$SEARX_SETTINGS"
log_ok "Wrote ${SEARX_SETTINGS}."
}

View File

@ -0,0 +1,68 @@
#!/bin/bash
# The SearXNG compose stack and settings files.
#
# Sourced by setup_searxng.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.
write_stack() {
ensure_dir "$SEARX_CONFIG_DIR"
reclaim_config_ownership
cat >"$SEARX_COMPOSE" <<EOF
# Managed by setup_searxng.sh — do not edit by hand.
services:
valkey:
container_name: ${VALKEY_CONTAINER}
image: valkey/valkey:8-alpine
# --bind is load-bearing: with host networking there is no bridge to hide
# behind, and upstream's own compose omits it.
command: valkey-server --bind 127.0.0.1 --port ${VALKEY_PORT} --save 30 1 --appendonly no
network_mode: host
restart: unless-stopped
volumes:
- valkey-data:/data
cap_drop: [ALL]
cap_add: [SETGID, SETUID, DAC_OVERRIDE]
searxng:
container_name: ${SEARX_CONTAINER}
# PINNED BY DIGEST, deliberately not :latest. Every non-obvious thing this
# file works around was established empirically against THIS image
# (2026.8.4): granian binds :: rather than the documented 127.0.0.1, the key
# is valkey.url not redis.url, server.bind_address is inert, the entrypoint
# chowns the config to uid 977, cap_drop breaks the config read, and
# public_instance force-enables link_token. A silent :latest bump can
# invalidate any of those and the guards would fail closed with a mystery.
# To upgrade: change the digest, re-run setup, re-check status.
image: ${SEARX_IMAGE}
network_mode: host
restart: unless-stopped
depends_on: [valkey]
volumes:
- ${SEARX_CONFIG_DIR}:/etc/searxng:rw
environment:
# server.bind_address in settings.yml is INERT in this image (it is only
# read under __main__, i.e. the Flask dev server). granian is the actual
# server and it binds :: by default -- verified empirically, despite its
# own docs claiming 127.0.0.1. These two vars are the only thing keeping
# this off the LAN.
- GRANIAN_HOST=127.0.0.1
- GRANIAN_PORT=${SEARX_PORT}
- SEARXNG_BASE_URL=https://${SEARX_DOMAIN}/
# No cap_drop here. The entrypoint starts as root to chown -R /etc/searxng
# and read the settings before dropping to uid 977, so dropping ALL caps
# (even re-adding CHOWN/SETGID/SETUID) loses DAC_OVERRIDE/FOWNER and the
# worker dies with "[Errno 13] Permission denied: /etc/searxng/settings.yml".
# Verified empirically: identical run without cap_drop has zero perm errors.
logging:
driver: json-file
options: { max-size: "1m", max-file: "1" }
volumes:
valkey-data:
EOF
log_ok "Wrote ${SEARX_COMPOSE}."
write_searx_settings
write_searx_limiter
}

View File

@ -0,0 +1,105 @@
#!/bin/bash
# Readiness polling, loopback assertion and stack startup.
#
# Sourced by setup_searxng.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.
# --- Phase 3/4: start -------------------------------------------------------
# Sends the Host header the edge will actually forward, and requires a
# non-empty body. A bare "curl http://127.0.0.1:PORT/" against a host-matcher
# misconfiguration returns an empty 200 — it passes while every real request
# serves a blank page.
wait_for_site() {
local _ size
for _ in $(seq 1 60); do
# Browser-shaped headers: without them botdetection answers 429 and this
# readiness probe would spin for its full 60s against a healthy backend.
size="$(curl -s --compressed -o /dev/null -w '%{size_download}' \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: none' -H 'Sec-Fetch-Dest: document' \
-H "Host: ${SEARX_DOMAIN}" "http://127.0.0.1:${SEARX_PORT}/" 2>/dev/null || echo 0)"
if [[ ${size:-0} -gt 0 ]]; then
return 0
fi
sleep 1
done
return 1
}
wait_for_valkey() {
local _ out
for _ in $(seq 1 30); do
out="$(docker exec "$VALKEY_CONTAINER" valkey-cli -h 127.0.0.1 -p "$VALKEY_PORT" ping 2>/dev/null || true)"
if [[ $out == "PONG" ]]; then
return 0
fi
sleep 1
done
return 1
}
# These containers share the host network namespace with the public edge, so a
# misconfiguration does not fail locally — it quietly exposes an unfronted
# service to the whole LAN, or steals a share of :80/:443 from every other site
# on the box. Gate on it rather than trust the config to stay correct.
assert_loopback_only() {
local container="$1" port="$2" pid listeners
pid="$(docker inspect -f '{{.State.Pid}}' "$container" 2>/dev/null || echo "")"
[[ -n $pid && $pid != "0" ]] || die "Could not read the ${container} PID."
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
# Demand positive evidence FIRST. Asserting only the absence of a bad bind
# fails open: if `ss` returns nothing — a stale PID, or sudo -n unavailable —
# every "is it bad?" test misses and the guard reports success having looked
# at nothing.
if ! grep -qE '(^|[[:space:]])127\.0\.0\.1:'"${port}"'([[:space:]]|$)' <<<"$listeners"; then
docker stop "$container" >/dev/null 2>&1 || true
die "Could not confirm ${container} listens on 127.0.0.1:${port}. Container stopped."
fi
if grep -qE ':(80|443)\b' <<<"$listeners"; then
docker stop "$container" >/dev/null 2>&1 || true
die "${container} bound :80/:443 — it would contend with ${CADDY_CONTAINER}. Container stopped."
fi
# Reject *, 0.0.0.0 AND [::] — granian's real default is ::, which a
# 0.0.0.0-only check would sail straight past.
if grep -qE '(\*|0\.0\.0\.0|\[::\]):'"${port}"'\b' <<<"$listeners"; then
docker stop "$container" >/dev/null 2>&1 || true
die "${container} bound ${port} on all interfaces, not loopback. Container stopped."
fi
log_ok "${container} listens on loopback:${port} only — no contention, not LAN-exposed."
}
start_stack() {
log_info "Starting valkey + searxng…"
docker compose -f "$SEARX_COMPOSE" up -d
# `up -d` is a no-op when only a BIND-MOUNTED config file changed — compose
# compares the compose spec, not the files it mounts. settings.yml and
# limiter.toml are read once at startup, so without an explicit restart the
# container keeps serving the previous config and every verification below
# silently tests the OLD deployment. (Hit for real: limiter.toml was written
# at 15:06 while the container had been running since 15:02, so botdetection
# kept 429ing with "missing config file".)
log_info "Restarting searxng to pick up settings.yml / limiter.toml…"
docker restart "$SEARX_CONTAINER" >/dev/null
if wait_for_valkey; then
log_ok "valkey answering PING on 127.0.0.1:${VALKEY_PORT}."
else
die "valkey did not become ready — the limiter would silently no-op."
fi
if wait_for_site; then
log_ok "SearXNG answering on http://127.0.0.1:${SEARX_PORT}/."
else
docker stop "$SEARX_CONTAINER" >/dev/null 2>&1 || true
die "SearXNG did not become reachable on 127.0.0.1:${SEARX_PORT} (container stopped)."
fi
assert_loopback_only "$VALKEY_CONTAINER" "$VALKEY_PORT"
assert_loopback_only "$SEARX_CONTAINER" "$SEARX_PORT"
}

View File

@ -0,0 +1,186 @@
#!/bin/bash
# The status subcommand and its HTTP, container and header checks.
#
# Sourced by setup_searxng.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.
# --- 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 with a non-empty body, else 1.
# The body-size check matters: a host-matcher misconfiguration answers 200
# with nothing in it, which a status-only check would call healthy.
# Certificates are NOT skipped — `curl -k` would report a failed-ACME cert as
# healthy, which is exactly the green-while-broken this exists to catch.
# Browser-shaped headers are REQUIRED, not cosmetic. botdetection runs a
# separate check per header and 429s on the FIRST one that fails, so the full
# set below must be sent every time. All four matter:
# Accept-Language -> http_accept_language (omitting this alone 429s)
# Accept-Encoding -> http_accept_encoding (needs gzip or deflate)
# Accept -> http_accept
# Sec-Fetch-* -> http_sec_fetch (302-redirects when invalid)
# Diagnosing which one bit is easy but non-obvious: set `debug: true` under
# general: in settings.yml, restart, and the log prints
# "NOT OK (searx.botdetection.<method>)" naming the exact check.
# (Observed: dropping only Accept-Language turned a healthy 200 into a 429.)
local url="$1" out code size
out="$(curl -s --compressed -o /dev/null -w '%{http_code} %{size_download}' --max-time 10 \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Sec-Fetch-Mode: navigate' \
-H 'Sec-Fetch-Site: none' \
-H 'Sec-Fetch-Dest: document' \
${2:+-H "Host: $2"} "$url" 2>/dev/null || echo "000 0")"
read -r code size <<<"$out"
[[ $code == "200" && ${size:-0} -gt 0 ]] && echo 0 || echo 1
}
check_container() {
local name="$1" port="$2" pid listeners
if ! docker ps --format '{{.Names}}' | grep -qx "$name"; then
status_line 1 "${name} container not running"
return
fi
status_line 0 "${name} container running"
pid="$(docker inspect -f '{{.State.Pid}}' "$name" 2>/dev/null || echo "")"
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
if [[ -z $listeners ]]; then
status_line 1 "${name}: could not read listeners (needs sudo -n) — binding UNVERIFIED"
elif grep -qE '(\*|0\.0\.0\.0|\[::\]):'"${port}"'\b' <<<"$listeners"; then
status_line 1 "${name} is bound to ALL INTERFACES on ${port} — LAN-exposed"
elif grep -qE '(^|[[:space:]])127\.0\.0\.1:'"${port}"'([[:space:]]|$)' <<<"$listeners"; then
status_line 0 "${name} listens on loopback:${port} only"
else
status_line 1 "${name} not listening on ${port} as expected"
fi
}
# Duplicated headers are the classic silent A+ killer, so count them rather than
# merely checking presence.
check_headers() {
local headers out h count
# Same browser-header requirement as check_http — a 429 carries none of these
# headers, so a bare curl would report all five as MISSING on a healthy site.
out="$(curl -sI --compressed --max-time 10 \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: none' -H 'Sec-Fetch-Dest: document' \
"https://${SEARX_DOMAIN}/" 2>/dev/null || true)"
if [[ -z $out ]]; then
status_line 1 "could not fetch headers from https://${SEARX_DOMAIN}/"
return
fi
headers=(content-security-policy strict-transport-security
x-content-type-options referrer-policy permissions-policy)
for h in "${headers[@]}"; do
count="$(grep -ci "^${h}:" <<<"$out" || true)"
if [[ $count -eq 1 ]]; then
status_line 0 "header ${h}: exactly 1"
elif [[ $count -eq 0 ]]; then
status_line 1 "header ${h}: MISSING"
else
status_line 1 "header ${h}: DUPLICATED (${count}) — costs the A+ grade"
fi
done
}
status_cmd() {
print_setup_header "SearXNG status"
if has_cmd docker; then
status_line 0 "docker present"
else
status_line 1 "docker missing"
fi
# NOTE: deliberately no ownership/mode assertion on settings.yml — the
# entrypoint chowns the bind mount to uid 977, so a "must be kuhy-owned,
# mode 600" check would false-fail on every run after first start.
if [[ -f $SEARX_SETTINGS ]]; then
status_line 0 "settings.yml present"
else
status_line 1 "settings.yml missing — run setup"
fi
# Its absence is not cosmetic: with no limiter.toml there are no
# trusted_proxies, so botdetection 429s every request including the homepage.
if [[ -f $SEARX_LIMITER ]]; then
status_line 0 "limiter.toml present"
else
status_line 1 "limiter.toml missing — botdetection will 429 everything"
fi
check_container "$VALKEY_CONTAINER" "$VALKEY_PORT"
check_container "$SEARX_CONTAINER" "$SEARX_PORT"
# The limiter silently no-ops when valkey is unreachable, so a working search
# does NOT prove the limiter works. Check the backend directly.
local ping
ping="$(docker exec "$VALKEY_CONTAINER" valkey-cli -h 127.0.0.1 -p "$VALKEY_PORT" ping 2>/dev/null || true)"
if [[ $ping == "PONG" ]]; then
status_line 0 "valkey reachable — limiter backend live"
else
status_line 1 "valkey NOT reachable — the limiter is silently disabled"
fi
status_line "$(check_http "http://127.0.0.1:${SEARX_PORT}/" "$SEARX_DOMAIN")" \
"local SearXNG (127.0.0.1:${SEARX_PORT}, Host: ${SEARX_DOMAIN})"
if [[ -f $SEARX_SNIPPET ]]; then
status_line 0 "Caddy snippet present"
else
status_line 1 "Caddy snippet missing"
fi
if getent hosts "$SEARX_DOMAIN" >/dev/null; then
status_line 0 "${SEARX_DOMAIN} resolves"
else
status_line 1 "${SEARX_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${SEARX_DOMAIN}/")" \
"external https://${SEARX_DOMAIN}/"
check_headers
# A loading front page proves nothing about the actual product. Egress is the
# fragile part on this host (bridge networking has no outbound access at all),
# so run a real query and require real results. Uses the loopback JSON API,
# which pass_ip exempts from botdetection.
local json hits
json="$(curl -s --compressed --max-time 30 \
"http://127.0.0.1:${SEARX_PORT}/search?q=arch+linux&format=json" 2>/dev/null || true)"
hits="$(grep -o '"url"' <<<"$json" | wc -l)"
if [[ ${hits:-0} -gt 0 ]]; then
status_line 0 "live search returned ${hits} results (engines reachable)"
else
status_line 1 "live search returned NO results — check egress/engines"
fi
# Surfaces engines that are failing rather than merely slow; these are the
# candidates for pruning.
local dead
dead="$(grep -oE '"unresponsive_engines": \[\[[^]]*' <<<"$json" | head -c 300 || true)"
[[ -n $dead ]] && log_info "unresponsive engines: ${dead#*: }"
# After pruning, general search is served by google cse alone (google/bing
# are inactive: true upstream and only answer to !go / !bi). That is a single
# point of failure worth naming explicitly rather than discovering as "no
# results", so check the engine that is actually carrying the category.
if [[ ${hits:-0} -eq 0 ]]; then
log_warn "general search has no working engine — try: !go <query> / !bi <query>,"
log_warn "or re-enable an engine in the 'engines:' block of ${SEARX_SETTINGS}"
fi
log_info "Not checked here (needs another machine): the JSON API under bot"
log_info "detection. Run from your phone on cellular, not from this host:"
log_info " curl 'https://${SEARX_DOMAIN}/search?q=test&format=json'"
}

View File

@ -107,373 +107,12 @@ build_solver() {
log_ok "Solver built to ${DICE_SRC}/dist."
}
# --- Phase 3: the static-serve stack ----------------------------------------
write_serve_stack() {
ensure_dir "$DICE_DATA_DIR"
cat >"$DICE_COMPOSE" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
services:
${DICE_CONTAINER}:
image: caddy:2.8
container_name: ${DICE_CONTAINER}
restart: unless-stopped
# host networking is REQUIRED, not a style choice: the nftables forward
# chain is policy drop with no accept rules, so a bridge-networked
# container has no outbound egress at all.
network_mode: host
volumes:
- ${DICE_SRC}/dist:/srv:ro
- ./Caddyfile:/etc/caddy/Caddyfile:ro
EOF
cat >"$DICE_INNER_CADDY" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
# Static file server on loopback; fronted by ${CADDY_CONTAINER} on the public
# domain.
#
# admin off is REQUIRED: this container shares the host network namespace with
# ${CADDY_CONTAINER}, so without it both would listen on the admin API (:2019)
# and a 'caddy reload' aimed at the edge could be applied here instead — which
# would make this process grab 80/443 and run its own ACME.
#
# auto_https off and the explicit http:// scheme are EQUALLY required, and this
# was found the hard way. A site address of "127.0.0.1:${DICE_PORT}" reads as a
# HOSTNAME, so Caddy turns on automatic HTTPS for it: it issues a local
# certificate, serves TLS on ${DICE_PORT} (so the plain-HTTP health check fails)
# and — the real damage — starts an HTTP->HTTPS redirect listener on :80. Under
# host networking that binds *:80 next to the edge, and SO_REUSEPORT then splits
# inbound HTTP between the two, which would intermittently break ACME
# challenges for every domain on this host.
#
# The site address is port-only and the loopback restriction is done with
# "bind". These are two different things and using the wrong one breaks in a way
# that looks like it works:
#
# A site address of "http://127.0.0.1:${DICE_PORT}" sets a host MATCHER of
# 127.0.0.1. ${CADDY_CONTAINER} forwards the original "Host:
# ${DICE_DOMAIN}" header, which then matches no route, and Caddy answers 200
# with an empty body. A local health check passes (curl sends Host:
# 127.0.0.1) while every real request serves a blank page.
#
# ":${DICE_PORT}" matches any Host, and "bind 127.0.0.1" restricts the
# listener itself — which the address never did. Without bind, host
# networking would expose this unfronted server to the whole LAN.
{
admin off
auto_https off
}
:${DICE_PORT} {
bind 127.0.0.1
root * /srv
# Single-page bundle: unknown paths should serve the app, not 404.
try_files {path} /index.html
file_server
encode gzip
}
EOF
log_ok "Wrote ${DICE_COMPOSE} and ${DICE_INNER_CADDY}."
}
# --- Phase 4: front it on the public domain ---------------------------------
write_snippet() {
cat >"$DICE_SNIPPET" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
${DICE_DOMAIN} {
reverse_proxy 127.0.0.1:${DICE_PORT}
}
EOF
log_ok "Wrote ${DICE_SNIPPET}."
}
# --- Phase 5: start ---------------------------------------------------------
# Sends the Host header the edge will actually forward, and requires a
# non-empty body. A bare "curl http://127.0.0.1:PORT/" sends Host: 127.0.0.1
# and returns an empty 200 against a host-matcher misconfiguration — it passes
# while every real request serves a blank page. Ask the question the edge asks.
wait_for_site() {
local _ size
for _ in $(seq 1 30); do
size="$(curl -s -o /dev/null -w '%{size_download}' \
-H "Host: ${DICE_DOMAIN}" "http://127.0.0.1:${DICE_PORT}/" 2>/dev/null || echo 0)"
if [[ ${size:-0} -gt 0 ]]; then
return 0
fi
sleep 1
done
return 1
}
# This container shares the host network namespace with the public edge, so a
# misconfiguration here does not fail locally — it quietly steals a share of
# :80 or :443 from every other site on the box. Gate on it rather than trust
# the config to stay correct.
assert_no_edge_conflict() {
local pid listeners
pid="$(docker inspect -f '{{.State.Pid}}' "$DICE_CONTAINER" 2>/dev/null || echo "")"
[[ -n $pid && $pid != "0" ]] || die "Could not read the ${DICE_CONTAINER} PID."
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
# Demand positive evidence FIRST. Asserting only the absence of :80/:443
# fails open: if `ss` returns nothing — a stale PID after a restart, or
# sudo -n unavailable — every "is it bad?" test misses and the guard happily
# reports success without having looked at anything.
if ! grep -qE '(^|[[:space:]])127\.0\.0\.1:'"${DICE_PORT}"'([[:space:]]|$)' <<<"$listeners"; then
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "Could not confirm ${DICE_CONTAINER} listens on 127.0.0.1:${DICE_PORT}. Container stopped."
fi
if grep -qE ':(80|443)\b' <<<"$listeners"; then
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "${DICE_CONTAINER} bound :80/:443 — it would contend with ${CADDY_CONTAINER}. Container stopped."
fi
# Must be on loopback, not 0.0.0.0/*: host networking would otherwise expose
# the unfronted static server to the whole LAN.
if grep -qE '(\*|0\.0\.0\.0):'"${DICE_PORT}"'\b' <<<"$listeners"; then
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "${DICE_CONTAINER} bound ${DICE_PORT} on all interfaces, not loopback. Container stopped."
fi
log_ok "${DICE_CONTAINER} listens on loopback:${DICE_PORT} only — no contention, not LAN-exposed."
}
start_site() {
log_info "Starting the ${DICE_CONTAINER} container…"
docker compose -f "$DICE_COMPOSE" up -d
if wait_for_site; then
log_ok "Solver answering on http://127.0.0.1:${DICE_PORT}/."
else
docker stop "$DICE_CONTAINER" >/dev/null 2>&1 || true
die "Solver did not become reachable on 127.0.0.1:${DICE_PORT} (container stopped)."
fi
assert_no_edge_conflict
}
# --- Phase 6: 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 7: auto-rebuild on commit ----------------------------------------
# The build runs in a memory-capped systemd user unit rather than inside the
# git hook. MemorySwapMax=0 is required, not cosmetic: this box has ~4 GB of
# zram (swap held IN ram), so a memory-limited cgroup without it thrashes zram
# instead of dying cleanly, and freezes the machine. A git hook running tsc and
# vite is precisely the scenario that costs.
install_autorebuild() {
ensure_dir "$UNIT_DIR"
cat >"$UNIT_FILE" <<EOF
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
[Unit]
Description=Rebuild the KCD2 dice solver static bundle
[Service]
Type=oneshot
WorkingDirectory=${DICE_SRC}
ExecStart=${DICE_BUILD}
MemoryMax=3G
MemorySwapMax=0
EOF
systemctl --user daemon-reload
log_ok "Installed ${UNIT_FILE}."
[[ -d "${REPO_ROOT}/.git" ]] || die "${REPO_ROOT} is not a git repository."
cat >"$HOOK_FILE" <<EOF
#!/bin/bash
# Managed by setup_kcd2_dice_solver.sh — do not edit by hand.
# Republishes https://${DICE_DOMAIN}/ when main gains solver changes.
[[ "\$(git rev-parse --abbrev-ref HEAD)" == main ]] || exit 0
git diff --name-only HEAD~1 HEAD -- kcd2_dice_solver/ | grep -q . || exit 0
# --no-block so the commit is never slowed, || true so systemd can never fail it.
systemctl --user start --no-block ${UNIT_NAME} || true
EOF
chmod +x "$HOOK_FILE"
log_ok "Installed ${HOOK_FILE}."
}
# --- Phase 8: firewall ------------------------------------------------------
# setup_wireguard_ssh.sh owns /etc/nftables.conf and regenerates it from
# scratch — `flush ruleset` and all — on every run. That is fine on a quiet
# machine and rude on a busy one: it momentarily drops the whole ruleset while
# games, VPN links and long-lived connections are relying on it. Since the only
# thing this deployment needs is 80/443 already being accepted, check first and
# only pay for the regeneration when the rule is genuinely missing.
# Exact token membership rather than a regex over the rule text: a loose
# pattern would also match "8080, 4433" and wrongly conclude the ports are open.
web_ports_open() {
local line ports
while read -r line; do
# Strip everything but digits and commas, then test for whole tokens.
ports=",${line//[^0-9,]/},"
if [[ $ports == *,80,* && $ports == *,443,* ]]; then
return 0
fi
done < <(sudo -n nft list ruleset 2>/dev/null | grep -oE 'tcp dport \{[^}]*\}')
return 1
}
ensure_firewall() {
if web_ports_open; then
log_ok "Ports 80/443 already accepted — leaving the ruleset untouched."
return 0
fi
log_info "Opening ports 80/443 via setup_wireguard_ssh.sh…"
sudo bash "$WG_SCRIPT" allow-web
}
# --- Phase 9: report --------------------------------------------------------
print_report() {
cat <<EOF
============================================================================
KCD2 dice solver deployed.
============================================================================
Solver : https://${DICE_DOMAIN}/
Auto-rebuild: committing to main with changes under kcd2_dice_solver/ starts
${UNIT_NAME}, which rebuilds dist/ in place.
Watch it: journalctl --user -u ${UNIT_NAME} -f
Force it: systemctl --user start ${UNIT_NAME}
NOTE: the rebuild builds the WORKING TREE, not the commit. An unrelated
uncommitted edit that happens to be present when it runs will ship to the live
site. Commit or set aside unrelated work before triggering a rebuild.
Acceptance test (do this on your phone):
Turn Wi-Fi OFF (use cellular) and open https://${DICE_DOMAIN}/ —
all 43 dice should be on one screen and tappable.
============================================================================
EOF
}
setup_cmd() {
print_setup_header "KCD2 dice solver setup"
preflight
build_solver
write_serve_stack
# The snippet goes into the SHARED sites/ directory, so it is written only
# after the backend is up and verified. Writing it first means a failure in
# start_site leaves an orphan behind that the next `caddy reload` from any
# other service picks up — the edge then serves this domain as a 502 and
# starts ACME retries for a host with no backend.
start_site
write_snippet
reload_caddy
install_autorebuild
ensure_firewall
print_report
log_ok "KCD2 dice solver 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 with a non-empty body, else 1.
# The body-size check matters: a host-matcher misconfiguration answers 200
# with nothing in it, which a status-only check would call healthy.
#
# Certificates are NOT skipped for https URLs — `curl -k` would report an
# expired or failed-ACME cert as a healthy site, which is precisely the kind
# of green-while-broken this command exists to catch. The loopback check runs
# over plain http, so it needs no exception.
local url="$1" out code size
out="$(curl -s -o /dev/null -w '%{http_code} %{size_download}' --max-time 10 \
${2:+-H "Host: $2"} "$url" 2>/dev/null || echo "000 0")"
read -r code size <<<"$out"
[[ $code == "200" && ${size:-0} -gt 0 ]] && echo 0 || echo 1
}
status_cmd() {
print_setup_header "KCD2 dice solver 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 "${DICE_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 "$DICE_CONTAINER"; then
status_line 0 "${DICE_CONTAINER} container running"
local pid listeners
pid="$(docker inspect -f '{{.State.Pid}}' "$DICE_CONTAINER" 2>/dev/null || echo "")"
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
if grep -qE ':(80|443)\b' <<<"$listeners"; then
status_line 1 "${DICE_CONTAINER} is CONTENDING for :80/:443 with ${CADDY_CONTAINER}"
else
status_line 0 "${DICE_CONTAINER} listens only on ${DICE_PORT}"
fi
else
status_line 1 "${DICE_CONTAINER} container not running"
fi
status_line "$(check_http "http://127.0.0.1:${DICE_PORT}/" "$DICE_DOMAIN")" \
"local static server (127.0.0.1:${DICE_PORT}, Host: ${DICE_DOMAIN})"
if [[ -f $DICE_SNIPPET ]]; then
status_line 0 "Caddy snippet present"
else
status_line 1 "Caddy snippet missing"
fi
if getent hosts "$DICE_DOMAIN" >/dev/null; then
status_line 0 "${DICE_DOMAIN} resolves"
else
status_line 1 "${DICE_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${DICE_DOMAIN}/")" \
"external https://${DICE_DOMAIN}/"
# The hook lives in .git/hooks, which is not version-controlled, so it is
# lost on a fresh clone and must be checked rather than assumed. Spelled as
# an explicit if: with two conditions, A && B || C really would misfire.
if [[ -x $HOOK_FILE ]] && grep -q "$UNIT_NAME" "$HOOK_FILE" 2>/dev/null; then
status_line 0 "post-commit auto-rebuild hook installed"
else
status_line 1 "post-commit hook missing — re-run setup"
fi
if [[ -f $UNIT_FILE ]]; then
status_line 0 "${UNIT_NAME} installed"
else
status_line 1 "${UNIT_NAME} missing — re-run setup"
fi
if systemctl --user is-failed --quiet "$UNIT_NAME"; then
status_line 1 "last auto-rebuild FAILED — journalctl --user -u ${UNIT_NAME}"
else
status_line 0 "no failed auto-rebuild recorded"
fi
# "not failed" also covers "never ran", so check the artefact rather than the
# unit: if any source file is newer than the published bundle, the hook is
# not firing and the site is quietly serving an old build.
local newest_src
newest_src="$(find "${DICE_SRC}/src" "${DICE_SRC}/index.html" -type f -newer \
"${DICE_SRC}/dist/index.html" -print -quit 2>/dev/null || true)"
if [[ -n $newest_src ]]; then
status_line 1 "published bundle is STALE (e.g. ${newest_src#"${DICE_SRC}/"}) — run: systemctl --user start ${UNIT_NAME}"
else
status_line 0 "published bundle is up to date with src/"
fi
}
# shellcheck source=lib/kcd2_serve.sh
source "$SCRIPT_DIR/lib/kcd2_serve.sh"
# shellcheck source=lib/kcd2_expose.sh
source "$SCRIPT_DIR/lib/kcd2_expose.sh"
# shellcheck source=lib/kcd2_autorebuild.sh
source "$SCRIPT_DIR/lib/kcd2_autorebuild.sh"
main() {
local cmd="${1:-setup}"

View File

@ -148,747 +148,19 @@ reclaim_config_ownership() {
done
}
write_stack() {
ensure_dir "$SEARX_CONFIG_DIR"
reclaim_config_ownership
# shellcheck source=lib/searxng_stack.sh
source "$SCRIPT_DIR/lib/searxng_stack.sh"
# shellcheck source=lib/searxng_settings.sh
source "$SCRIPT_DIR/lib/searxng_settings.sh"
# shellcheck source=lib/searxng_limiter.sh
source "$SCRIPT_DIR/lib/searxng_limiter.sh"
# shellcheck source=lib/searxng_start.sh
source "$SCRIPT_DIR/lib/searxng_start.sh"
# shellcheck source=lib/searxng_expose.sh
source "$SCRIPT_DIR/lib/searxng_expose.sh"
# shellcheck source=lib/searxng_status.sh
source "$SCRIPT_DIR/lib/searxng_status.sh"
cat >"$SEARX_COMPOSE" <<EOF
# Managed by setup_searxng.sh — do not edit by hand.
services:
valkey:
container_name: ${VALKEY_CONTAINER}
image: valkey/valkey:8-alpine
# --bind is load-bearing: with host networking there is no bridge to hide
# behind, and upstream's own compose omits it.
command: valkey-server --bind 127.0.0.1 --port ${VALKEY_PORT} --save 30 1 --appendonly no
network_mode: host
restart: unless-stopped
volumes:
- valkey-data:/data
cap_drop: [ALL]
cap_add: [SETGID, SETUID, DAC_OVERRIDE]
searxng:
container_name: ${SEARX_CONTAINER}
# PINNED BY DIGEST, deliberately not :latest. Every non-obvious thing this
# file works around was established empirically against THIS image
# (2026.8.4): granian binds :: rather than the documented 127.0.0.1, the key
# is valkey.url not redis.url, server.bind_address is inert, the entrypoint
# chowns the config to uid 977, cap_drop breaks the config read, and
# public_instance force-enables link_token. A silent :latest bump can
# invalidate any of those and the guards would fail closed with a mystery.
# To upgrade: change the digest, re-run setup, re-check status.
image: ${SEARX_IMAGE}
network_mode: host
restart: unless-stopped
depends_on: [valkey]
volumes:
- ${SEARX_CONFIG_DIR}:/etc/searxng:rw
environment:
# server.bind_address in settings.yml is INERT in this image (it is only
# read under __main__, i.e. the Flask dev server). granian is the actual
# server and it binds :: by default -- verified empirically, despite its
# own docs claiming 127.0.0.1. These two vars are the only thing keeping
# this off the LAN.
- GRANIAN_HOST=127.0.0.1
- GRANIAN_PORT=${SEARX_PORT}
- SEARXNG_BASE_URL=https://${SEARX_DOMAIN}/
# No cap_drop here. The entrypoint starts as root to chown -R /etc/searxng
# and read the settings before dropping to uid 977, so dropping ALL caps
# (even re-adding CHOWN/SETGID/SETUID) loses DAC_OVERRIDE/FOWNER and the
# worker dies with "[Errno 13] Permission denied: /etc/searxng/settings.yml".
# Verified empirically: identical run without cap_drop has zero perm errors.
logging:
driver: json-file
options: { max-size: "1m", max-file: "1" }
volumes:
valkey-data:
EOF
log_ok "Wrote ${SEARX_COMPOSE}."
local secret
secret="$(read_or_make_secret)"
cat >"$SEARX_SETTINGS" <<EOF
# Managed by setup_searxng.sh — do not edit by hand.
#
# "Vanilla" constraint: everything here is a SETTINGS change. No ui.static_path,
# no templates_path, no injected CSS/JS -- the shipped static files must keep
# matching upstream.
use_default_settings: true
general:
instance_name: "${SEARX_DOMAIN}"
# Keeps a public instance from advertising an admin contact to scrapers.
contact_url: false
enable_metrics: true
server:
port: ${SEARX_PORT}
bind_address: "127.0.0.1" # inert under granian; kept for correctness/clarity
secret_key: "${secret}"
limiter: true
# public_instance is deliberately NOT set. It force-enables link_token, a
# browser-proof challenge that requires the client to fetch a probe resource —
# which makes /search?format=json unusable for any scripted client (it 429s or
# 302s forever, and no limiter.toml setting can override it because the flag
# forces it on). It exists to satisfy searx.space directory norms, and this
# instance is deliberately unlisted, so it costs the JSON API for nothing.
# Rate limiting and the image proxy are kept via their own keys below.
# Required by the strict CSP: proxying images keeps them same-origin so
# img-src can stay 'self' without breaking result thumbnails.
image_proxy: true
method: "POST"
search:
safe_search: 0
autocomplete: "duckduckgo"
default_lang: "en"
# json is enabled for programmatic/MCP use. Note this interacts with the
# limiter's bot detection -- see the off-host verification step.
formats:
- html
- json
outgoing:
# Caps the tail so one dead engine cannot hold up a whole search.
request_timeout: 3.0
max_request_timeout: 6.0
pool_connections: 100
pool_maxsize: 20
enable_http2: true
valkey:
# Key is valkey.url; redis.url still parses but emits a DeprecationWarning.
url: valkey://127.0.0.1:${VALKEY_PORT}/0
ui:
static_use_hash: true
infinite_scroll: false
query_in_title: true
# Engine pruning — MEASURED on this host (5+ varied queries, /stats + the
# unresponsive_engines field), not guessed. Each entry says why.
#
# Cross-checked against this host's own /etc/hosts blocklist first: pinterest
# resolves to 0.0.0.0 here (blackholed by generate_hosts_file.sh), so it fails
# for a LOCAL reason and would have been misdiagnosed as a slow/dead upstream.
# It is disabled to stop the pointless request, not because the engine is bad.
#
# Re-check periodically with:
# curl -s 'http://127.0.0.1:${SEARX_PORT}/search?q=test&format=json' \\
# | grep -o '"unresponsive_engines":.*'
# Engine pruning, kuhy-selected 2026-08-09 from the /preferences engine table:
# every engine that was erroring (CAPTCHA / access denied / timeout / parsing
# error / crash) plus the slow tail, across all categories.
#
# Retained on purpose: google cse, wikipedia/wikidata and the specialist
# lookups (arch linux wiki, github, stackexchange, pypi, ...).
#
# IMPORTANT about general search: the merged general view is served by
# google cse ALONE, and was before this pruning too. The plain google and bing
# engines are marked "inactive: true" upstream, meaning they only run when
# explicitly invoked with a bang (!go -> 20 results, !bi -> 10, both
# verified working). So the pruning removed only engines that were already
# contributing zero results -- but it also means general search has a single
# point of failure. If google cse ever starts erroring, general search returns
# nothing until another engine is enabled or !go/!bi is used.
#
# pinterest is blackholed to 0.0.0.0 by this host's own /etc/hosts
# (generate_hosts_file.sh) -- a LOCAL failure that looks identical to a dead
# upstream. Disabled to stop the pointless request, not because the engine is bad.
#
# USE "inactive: true", NOT "disabled: true". Straight from enginelib:
# disabled -> "disable BY DEFAULT ... will allow the user to manually
# activate it in the settings" (i.e. only the default for a
# fresh visitor; anyone with an existing preferences cookie keeps
# running the engine)
# inactive -> "Remove the engine from the settings (disabled & removed)"
# The first pass used "disabled" and the pruned engines kept executing for any
# browser session that already had a preferences cookie -- yandex images was
# still throwing JSONDecodeErrors in the log minutes after being "disabled".
#
# EXCEPTION -- brave and qwant use "disabled", not "inactive", ON PURPOSE.
# They own an outgoing connection pool that sibling engines reference by name
# ("network: brave" <- brave.images/.videos/.news; "network: qwant" <- qwant
# news/images/videos). "inactive" REMOVES the definition, so the siblings'
# lookup dies at startup with KeyError: 'qwant' and the container never comes
# up. "disabled" keeps the pool defined while hiding the engine from results.
# Pool owners in this image: brave, qwant, yandex, piped, yacy -- of which only
# brave and qwant are pruned here. Check before making any of the rest inactive:
# grep -B4 'network: <name>' /usr/local/searxng/searx/settings.yml
#
# Re-check periodically:
# curl -s 'http://127.0.0.1:8090/search?q=test&format=json' | grep -o '"unresponsive_engines":.*'
engines:
# === general ===
- { name: brave, disabled: true } # too many requests
- { name: duckduckgo, inactive: true } # CAPTCHA
- { name: startpage, inactive: true } # Suspended: CAPTCHA
- { name: dogpile, inactive: true } # access denied
- { name: encyclosearch, inactive: true } # timeout
- { name: fastbot, inactive: true } # access denied
- { name: fireball, inactive: true } # access denied
- { name: quark, inactive: true } # unexpected crash
- { name: qwant, disabled: true } # CAPTCHA
- { name: sogou, inactive: true } # CAPTCHA
- { name: tusksearch, inactive: true } # HTTP error
- { name: yahoo, inactive: true } # HTTP protocol error
- { name: yep, inactive: true } # access denied
- { name: naver, inactive: true } # 1.9s
- { name: baidu, inactive: true } # 1.7s
- { name: abcnyheter, inactive: true } # 1.5s
- { name: boardreader, inactive: true } # 1.5s
- { name: crowdview, inactive: true } # 1.0s
# === images === (keeping ONLY google cse images)
- { name: dogpile images, inactive: true } # access denied
- { name: findfiles images, inactive: true } # unexpected crash
- { name: library of congress, inactive: true } # parsing error
- { name: pinterest, inactive: true } # 0.0.0.0 in /etc/hosts (local)
- { name: qwant images, inactive: true } # CAPTCHA
- { name: tusksearch images, inactive: true } # HTTP error
- { name: wikicommons.images, inactive: true } # too many requests
- { name: yandex images, inactive: true } # parsing error
- { name: quark images, inactive: true } # 2.9s
- { name: 1x, inactive: true } # 2.5s
- { name: baidu images, inactive: true } # 2.5s
- { name: picjumbo, inactive: true } # 2.4s
- { name: naver images, inactive: true } # 2.3s
- { name: sogou images, inactive: true } # 2.0s
- { name: unsplash, inactive: true } # 1.2s
- { name: duckduckgo images, inactive: true }
- { name: flickr, inactive: true } # 1.0s
- { name: bing images, inactive: true } # cut for the sub-1s images goal
- { name: deviantart, inactive: true } # cut for the sub-1s images goal
- { name: openverse, inactive: true } # cut for the sub-1s images goal
- { name: pexels, inactive: true } # cut for the sub-1s images goal
- { name: artic, inactive: true } # cut for the sub-1s images goal
- { name: devicons, inactive: true } # cut for the sub-1s images goal
- { name: lucide, inactive: true } # cut for the sub-1s images goal
- { name: wallhaven, inactive: true } # cut for the sub-1s images goal
# Not in the /preferences list kuhy sent -- these only surfaced as
# unresponsive under load, same failure pattern, so pruned with the rest.
- { name: brave.images, inactive: true } # too many requests
- { name: startpage images, inactive: true } # Suspended: CAPTCHA
# === videos ===
- { name: 360search videos, inactive: true } # unexpected crash
- { name: acfun, inactive: true } # timeout
- { name: brave.videos, inactive: true } # too many requests
- { name: dogpile videos, inactive: true } # access denied
- { name: fireball videos, inactive: true } # access denied
- { name: niconico, inactive: true } # HTTP connection error
- { name: pixabay videos, inactive: true } # timeout
- { name: tusksearch videos, inactive: true } # HTTP error
- { name: vimeo, inactive: true } # access denied
- { name: youtube, inactive: true } # HTTP connection error
- { name: naver videos, inactive: true } # 2.4s
- { name: sogou videos, inactive: true } # 2.0s
- { name: iqiyi, inactive: true } # 1.3s
- { name: rumble, inactive: true } # 1.3s
# === news ===
- { name: bing news, inactive: true } # parsing error
- { name: brave.news, inactive: true } # too many requests
- { name: dogpile news, inactive: true } # access denied
- { name: fireball news, inactive: true } # access denied
- { name: google news, inactive: true } # Suspended: CAPTCHA
- { name: startpage news, inactive: true } # Suspended: CAPTCHA
- { name: tusksearch news, inactive: true } # HTTP error
- { name: sogou wechat, inactive: true } # 1.7s
- { name: naver news, inactive: true } # 1.7s
# === music ===
- { name: radio browser, inactive: true } # HTTP error
- { name: yandex music, inactive: true } # HTTP error
# === it ===
- { name: codeberg, inactive: true } # timeout
- { name: metacpan, inactive: true } # HTTP error
- { name: nixos wiki, inactive: true } # timeout
- { name: baidu kaifa, inactive: true } # 2.0s
- { name: gitea.com, inactive: true } # 1.8s
- { name: rubygems, inactive: true } # 1.1s
# === science ===
- { name: openairepublications, inactive: true } # 2.7s
- { name: openairedatasets, inactive: true } # 2.7s
# === files ===
- { name: 1337x, inactive: true } # HTTP connection error
- { name: btdigg, inactive: true } # 1.5s
- { name: findfiles, inactive: true } # 1.2s
- { name: kickass, inactive: true } # HTTP connection error (surfaced under load)
# === social media ===
- { name: 9gag, inactive: true } # access denied
- { name: tootfinder, inactive: true } # access denied
EOF
# 640, NOT 600. The entrypoint chowns this file to the container's searxng
# user (uid 977), but granian's worker runs as a different uid and only has
# GROUP access — mode 600 makes it unreadable and the worker dies with
# "[Errno 13] Permission denied: /etc/searxng/settings.yml". It still is not
# world-readable, so secret_key stays protected.
chmod 640 "$SEARX_SETTINGS"
log_ok "Wrote ${SEARX_SETTINGS}."
# Without this file SearXNG logs "missing config file:
# /etc/searxng/limiter.toml" and runs with no trusted_proxies, so the
# forwarded client IP is never trusted and botdetection 429s *everything*.
cat >"$SEARX_LIMITER" <<'EOF'
# Managed by setup_searxng.sh — do not edit by hand.
[botdetection]
ipv4_prefix = 32
ipv6_prefix = 48
# The edge (gitea-caddy) shares the host network namespace, so its requests
# arrive from loopback. Without 127.0.0.0/8 here the X-Forwarded-For that Caddy
# sends is ignored, every request looks like it came from the proxy itself, and
# rate limiting collapses onto a single bucket.
trusted_proxies = [
'127.0.0.0/8',
'::1',
]
[botdetection.ip_limit]
filter_link_local = false
# Off (the shipped default). link_token sends a probe the client must fetch to
# prove it renders HTML, which no scripted JSON client can satisfy. IP-based
# rate limiting below is unaffected and still applies.
link_token = false
[botdetection.ip_lists]
block_ip = []
# pass_ip bypasses ALL botdetection (including the Sec-Fetch/User-Agent probe
# headers) for these addresses.
#
# This is what makes search.formats = [html, json] usable. A scripted JSON
# client — an MCP server, a script — cannot send Sec-Fetch-Mode/Site/Dest, and
# botdetection 429s anything that lacks them, so WITHOUT this entry the JSON API
# is unreachable for every non-browser client. Verified: with browser headers a
# search returns 200 + results; the identical request without Sec-Fetch-* gets
# 429.
#
# Deliberately LOOPBACK ONLY. Requests arriving through the public edge carry
# the real client IP in X-Forwarded-For (trusted_proxies above), so they are
# still fully rate-limited — this exempts only tools running on this host.
pass_ip = [
'127.0.0.0/8',
'::1',
]
EOF
chmod 640 "$SEARX_LIMITER"
log_ok "Wrote ${SEARX_LIMITER}."
}
# --- Phase 3/4: start -------------------------------------------------------
# Sends the Host header the edge will actually forward, and requires a
# non-empty body. A bare "curl http://127.0.0.1:PORT/" against a host-matcher
# misconfiguration returns an empty 200 — it passes while every real request
# serves a blank page.
wait_for_site() {
local _ size
for _ in $(seq 1 60); do
# Browser-shaped headers: without them botdetection answers 429 and this
# readiness probe would spin for its full 60s against a healthy backend.
size="$(curl -s --compressed -o /dev/null -w '%{size_download}' \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: none' -H 'Sec-Fetch-Dest: document' \
-H "Host: ${SEARX_DOMAIN}" "http://127.0.0.1:${SEARX_PORT}/" 2>/dev/null || echo 0)"
if [[ ${size:-0} -gt 0 ]]; then
return 0
fi
sleep 1
done
return 1
}
wait_for_valkey() {
local _ out
for _ in $(seq 1 30); do
out="$(docker exec "$VALKEY_CONTAINER" valkey-cli -h 127.0.0.1 -p "$VALKEY_PORT" ping 2>/dev/null || true)"
if [[ $out == "PONG" ]]; then
return 0
fi
sleep 1
done
return 1
}
# These containers share the host network namespace with the public edge, so a
# misconfiguration does not fail locally — it quietly exposes an unfronted
# service to the whole LAN, or steals a share of :80/:443 from every other site
# on the box. Gate on it rather than trust the config to stay correct.
assert_loopback_only() {
local container="$1" port="$2" pid listeners
pid="$(docker inspect -f '{{.State.Pid}}' "$container" 2>/dev/null || echo "")"
[[ -n $pid && $pid != "0" ]] || die "Could not read the ${container} PID."
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
# Demand positive evidence FIRST. Asserting only the absence of a bad bind
# fails open: if `ss` returns nothing — a stale PID, or sudo -n unavailable —
# every "is it bad?" test misses and the guard reports success having looked
# at nothing.
if ! grep -qE '(^|[[:space:]])127\.0\.0\.1:'"${port}"'([[:space:]]|$)' <<<"$listeners"; then
docker stop "$container" >/dev/null 2>&1 || true
die "Could not confirm ${container} listens on 127.0.0.1:${port}. Container stopped."
fi
if grep -qE ':(80|443)\b' <<<"$listeners"; then
docker stop "$container" >/dev/null 2>&1 || true
die "${container} bound :80/:443 — it would contend with ${CADDY_CONTAINER}. Container stopped."
fi
# Reject *, 0.0.0.0 AND [::] — granian's real default is ::, which a
# 0.0.0.0-only check would sail straight past.
if grep -qE '(\*|0\.0\.0\.0|\[::\]):'"${port}"'\b' <<<"$listeners"; then
docker stop "$container" >/dev/null 2>&1 || true
die "${container} bound ${port} on all interfaces, not loopback. Container stopped."
fi
log_ok "${container} listens on loopback:${port} only — no contention, not LAN-exposed."
}
start_stack() {
log_info "Starting valkey + searxng…"
docker compose -f "$SEARX_COMPOSE" up -d
# `up -d` is a no-op when only a BIND-MOUNTED config file changed — compose
# compares the compose spec, not the files it mounts. settings.yml and
# limiter.toml are read once at startup, so without an explicit restart the
# container keeps serving the previous config and every verification below
# silently tests the OLD deployment. (Hit for real: limiter.toml was written
# at 15:06 while the container had been running since 15:02, so botdetection
# kept 429ing with "missing config file".)
log_info "Restarting searxng to pick up settings.yml / limiter.toml…"
docker restart "$SEARX_CONTAINER" >/dev/null
if wait_for_valkey; then
log_ok "valkey answering PING on 127.0.0.1:${VALKEY_PORT}."
else
die "valkey did not become ready — the limiter would silently no-op."
fi
if wait_for_site; then
log_ok "SearXNG answering on http://127.0.0.1:${SEARX_PORT}/."
else
docker stop "$SEARX_CONTAINER" >/dev/null 2>&1 || true
die "SearXNG did not become reachable on 127.0.0.1:${SEARX_PORT} (container stopped)."
fi
assert_loopback_only "$VALKEY_CONTAINER" "$VALKEY_PORT"
assert_loopback_only "$SEARX_CONTAINER" "$SEARX_PORT"
}
# --- Phase 5: front it on the public domain ---------------------------------
# Header syntax matters and is easy to get wrong:
# Header "value" -> "set" (REPLACES any existing value) <-- what we want
# +Header "value" -> "add" (appends, yielding duplicates)
# >Header "value" -> "replace" (substring search/replace WITHIN a value —
# NOT a header setter. Using it here silently
# produced no header at all: it adapts to
# {"replace": {"": [{"search_regexp": "..."}]}}
# and matches nothing. Verified via caddy adapt.)
# This matters because SearXNG sends X-Content-Type-Options and Referrer-Policy
# itself via default_http_headers (its Referrer-Policy is `no-referrer`, which
# differs from ours), so the bare/"set" form is required to override rather than
# duplicate them.
write_snippet() {
cat >"$SEARX_SNIPPET" <<EOF
# Managed by setup_searxng.sh — do not edit by hand.
${SEARX_DOMAIN} {
header {
# Bare name = "set" = replace. Do NOT prefix with '+' (appends, causing
# duplicate headers) or '>' (substring-replace, which sets nothing).
Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'; manifest-src 'self'"
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "geolocation=(), microphone=(), camera=(), interest-cohort=()"
# No HSTS preload: duckdns.org is a public suffix, so kuhy.duckdns.org is
# the registrable domain — preloading would force HTTPS on every sibling
# subdomain and is effectively irreversible. Not needed to clear A+.
-Server
}
reverse_proxy 127.0.0.1:${SEARX_PORT} {
# SearXNG's botdetection needs the real client IP. Without this it logs
# "X-Forwarded-For nor X-Real-IP header is set!" and 429s every request,
# including the front page. Paired with trusted_proxies in limiter.toml —
# both halves are required, neither works alone.
header_up X-Forwarded-For {http.request.remote.host}
header_up X-Real-IP {http.request.remote.host}
}
}
EOF
log_ok "Wrote ${SEARX_SNIPPET}."
}
# --- Phase 6: 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
rm -f "$SEARX_SNIPPET"
die "Caddy config invalid — snippet removed, edge left untouched."
fi
}
# --- Phase 7: firewall ------------------------------------------------------
# setup_wireguard_ssh.sh owns /etc/nftables.conf and regenerates it from scratch
# — `flush ruleset` and all — on every run, momentarily dropping the whole
# ruleset. Since all this needs is 80/443 already being accepted, check first
# and only pay for the regeneration when the rule is genuinely missing.
web_ports_open() {
local line ports
while read -r line; do
# Exact token membership: a loose regex would also match "8080, 4433".
ports=",${line//[^0-9,]/},"
if [[ $ports == *,80,* && $ports == *,443,* ]]; then
return 0
fi
done < <(sudo -n nft list ruleset 2>/dev/null | grep -oE 'tcp dport \{[^}]*\}')
return 1
}
ensure_firewall() {
if web_ports_open; then
log_ok "Ports 80/443 already accepted — leaving the ruleset untouched."
return 0
fi
log_info "Opening ports 80/443 via setup_wireguard_ssh.sh…"
sudo bash "$WG_SCRIPT" allow-web
}
# --- Phase 8: report --------------------------------------------------------
print_report() {
cat <<EOF
============================================================================
SearXNG deployed.
============================================================================
Search : https://${SEARX_DOMAIN}/
JSON : https://${SEARX_DOMAIN}/search?q=test&format=json
Next, in order:
1. Header check (each must print exactly 1):
for h in content-security-policy strict-transport-security \\
x-content-type-options referrer-policy permissions-policy; do
printf '%s: ' "\$h"
curl -sI https://${SEARX_DOMAIN}/ | grep -ci "^\$h:"
done
2. Mozilla Observatory scan of ${SEARX_DOMAIN} — that scan IS the A+ grade.
3. JSON API FROM ANOTHER MACHINE (phone on cellular, not this host):
curl 'https://${SEARX_DOMAIN}/search?q=test&format=json'
A from-host curl cannot surface bot-detection rejection. If this returns
403/429, fix the limiter allowlist — do NOT disable the limiter.
Acceptance test (do this on your phone):
Turn Wi-Fi OFF (use cellular) and run a real search at https://${SEARX_DOMAIN}/
============================================================================
EOF
}
setup_cmd() {
print_setup_header "SearXNG setup"
preflight
write_stack
# The snippet goes into the SHARED sites/ directory, so it is written only
# after the backend is up and verified. Writing it first means a failure in
# start_stack leaves an orphan behind that the next `caddy reload` from any
# other service picks up — the edge then serves this domain as a 502 and
# starts ACME retries for a host with no backend.
start_stack
write_snippet
reload_caddy
ensure_firewall
print_report
log_ok "SearXNG 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 with a non-empty body, else 1.
# The body-size check matters: a host-matcher misconfiguration answers 200
# with nothing in it, which a status-only check would call healthy.
# Certificates are NOT skipped — `curl -k` would report a failed-ACME cert as
# healthy, which is exactly the green-while-broken this exists to catch.
# Browser-shaped headers are REQUIRED, not cosmetic. botdetection runs a
# separate check per header and 429s on the FIRST one that fails, so the full
# set below must be sent every time. All four matter:
# Accept-Language -> http_accept_language (omitting this alone 429s)
# Accept-Encoding -> http_accept_encoding (needs gzip or deflate)
# Accept -> http_accept
# Sec-Fetch-* -> http_sec_fetch (302-redirects when invalid)
# Diagnosing which one bit is easy but non-obvious: set `debug: true` under
# general: in settings.yml, restart, and the log prints
# "NOT OK (searx.botdetection.<method>)" naming the exact check.
# (Observed: dropping only Accept-Language turned a healthy 200 into a 429.)
local url="$1" out code size
out="$(curl -s --compressed -o /dev/null -w '%{http_code} %{size_download}' --max-time 10 \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Sec-Fetch-Mode: navigate' \
-H 'Sec-Fetch-Site: none' \
-H 'Sec-Fetch-Dest: document' \
${2:+-H "Host: $2"} "$url" 2>/dev/null || echo "000 0")"
read -r code size <<<"$out"
[[ $code == "200" && ${size:-0} -gt 0 ]] && echo 0 || echo 1
}
check_container() {
local name="$1" port="$2" pid listeners
if ! docker ps --format '{{.Names}}' | grep -qx "$name"; then
status_line 1 "${name} container not running"
return
fi
status_line 0 "${name} container running"
pid="$(docker inspect -f '{{.State.Pid}}' "$name" 2>/dev/null || echo "")"
listeners="$(sudo -n ss -ltnp 2>/dev/null | grep "pid=${pid}," || true)"
if [[ -z $listeners ]]; then
status_line 1 "${name}: could not read listeners (needs sudo -n) — binding UNVERIFIED"
elif grep -qE '(\*|0\.0\.0\.0|\[::\]):'"${port}"'\b' <<<"$listeners"; then
status_line 1 "${name} is bound to ALL INTERFACES on ${port} — LAN-exposed"
elif grep -qE '(^|[[:space:]])127\.0\.0\.1:'"${port}"'([[:space:]]|$)' <<<"$listeners"; then
status_line 0 "${name} listens on loopback:${port} only"
else
status_line 1 "${name} not listening on ${port} as expected"
fi
}
# Duplicated headers are the classic silent A+ killer, so count them rather than
# merely checking presence.
check_headers() {
local headers out h count
# Same browser-header requirement as check_http — a 429 carries none of these
# headers, so a bare curl would report all five as MISSING on a healthy site.
out="$(curl -sI --compressed --max-time 10 \
-A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'Accept-Language: en-US,en;q=0.9' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Sec-Fetch-Mode: navigate' -H 'Sec-Fetch-Site: none' -H 'Sec-Fetch-Dest: document' \
"https://${SEARX_DOMAIN}/" 2>/dev/null || true)"
if [[ -z $out ]]; then
status_line 1 "could not fetch headers from https://${SEARX_DOMAIN}/"
return
fi
headers=(content-security-policy strict-transport-security
x-content-type-options referrer-policy permissions-policy)
for h in "${headers[@]}"; do
count="$(grep -ci "^${h}:" <<<"$out" || true)"
if [[ $count -eq 1 ]]; then
status_line 0 "header ${h}: exactly 1"
elif [[ $count -eq 0 ]]; then
status_line 1 "header ${h}: MISSING"
else
status_line 1 "header ${h}: DUPLICATED (${count}) — costs the A+ grade"
fi
done
}
status_cmd() {
print_setup_header "SearXNG status"
if has_cmd docker; then
status_line 0 "docker present"
else
status_line 1 "docker missing"
fi
# NOTE: deliberately no ownership/mode assertion on settings.yml — the
# entrypoint chowns the bind mount to uid 977, so a "must be kuhy-owned,
# mode 600" check would false-fail on every run after first start.
if [[ -f $SEARX_SETTINGS ]]; then
status_line 0 "settings.yml present"
else
status_line 1 "settings.yml missing — run setup"
fi
# Its absence is not cosmetic: with no limiter.toml there are no
# trusted_proxies, so botdetection 429s every request including the homepage.
if [[ -f $SEARX_LIMITER ]]; then
status_line 0 "limiter.toml present"
else
status_line 1 "limiter.toml missing — botdetection will 429 everything"
fi
check_container "$VALKEY_CONTAINER" "$VALKEY_PORT"
check_container "$SEARX_CONTAINER" "$SEARX_PORT"
# The limiter silently no-ops when valkey is unreachable, so a working search
# does NOT prove the limiter works. Check the backend directly.
local ping
ping="$(docker exec "$VALKEY_CONTAINER" valkey-cli -h 127.0.0.1 -p "$VALKEY_PORT" ping 2>/dev/null || true)"
if [[ $ping == "PONG" ]]; then
status_line 0 "valkey reachable — limiter backend live"
else
status_line 1 "valkey NOT reachable — the limiter is silently disabled"
fi
status_line "$(check_http "http://127.0.0.1:${SEARX_PORT}/" "$SEARX_DOMAIN")" \
"local SearXNG (127.0.0.1:${SEARX_PORT}, Host: ${SEARX_DOMAIN})"
if [[ -f $SEARX_SNIPPET ]]; then
status_line 0 "Caddy snippet present"
else
status_line 1 "Caddy snippet missing"
fi
if getent hosts "$SEARX_DOMAIN" >/dev/null; then
status_line 0 "${SEARX_DOMAIN} resolves"
else
status_line 1 "${SEARX_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${SEARX_DOMAIN}/")" \
"external https://${SEARX_DOMAIN}/"
check_headers
# A loading front page proves nothing about the actual product. Egress is the
# fragile part on this host (bridge networking has no outbound access at all),
# so run a real query and require real results. Uses the loopback JSON API,
# which pass_ip exempts from botdetection.
local json hits
json="$(curl -s --compressed --max-time 30 \
"http://127.0.0.1:${SEARX_PORT}/search?q=arch+linux&format=json" 2>/dev/null || true)"
hits="$(grep -o '"url"' <<<"$json" | wc -l)"
if [[ ${hits:-0} -gt 0 ]]; then
status_line 0 "live search returned ${hits} results (engines reachable)"
else
status_line 1 "live search returned NO results — check egress/engines"
fi
# Surfaces engines that are failing rather than merely slow; these are the
# candidates for pruning.
local dead
dead="$(grep -oE '"unresponsive_engines": \[\[[^]]*' <<<"$json" | head -c 300 || true)"
[[ -n $dead ]] && log_info "unresponsive engines: ${dead#*: }"
# After pruning, general search is served by google cse alone (google/bing
# are inactive: true upstream and only answer to !go / !bi). That is a single
# point of failure worth naming explicitly rather than discovering as "no
# results", so check the engine that is actually carrying the category.
if [[ ${hits:-0} -eq 0 ]]; then
log_warn "general search has no working engine — try: !go <query> / !bi <query>,"
log_warn "or re-enable an engine in the 'engines:' block of ${SEARX_SETTINGS}"
fi
log_info "Not checked here (needs another machine): the JSON API under bot"
log_info "detection. Run from your phone on cellular, not from this host:"
log_info " curl 'https://${SEARX_DOMAIN}/search?q=test&format=json'"
}
main() {
local cmd="${1:-setup}"

View File

@ -147,549 +147,15 @@ check_packages() {
fi
}
# ==========================================================================
# 3. Check for missing Broadcom firmware
# ==========================================================================
check_firmware() {
echo ""
log_info "Checking for missing Bluetooth firmware..."
# shellcheck source=lib/bt_adapter.sh
source "$SCRIPT_DIR/lib/bt_adapter.sh"
# shellcheck source=lib/bt_pairing.sh
source "$SCRIPT_DIR/lib/bt_pairing.sh"
# shellcheck source=lib/bt_audio.sh
source "$SCRIPT_DIR/lib/bt_audio.sh"
# shellcheck source=lib/bt_report.sh
source "$SCRIPT_DIR/lib/bt_report.sh"
local missing_fw
missing_fw=$(dmesg 2>/dev/null | grep -o "brcm/BCM[^ ']*\.hcd" | sort -u || true)
if [[ -z $missing_fw ]]; then
log_ok "No missing firmware detected in dmesg."
return 0
fi
local fw_name
for fw_name in $missing_fw; do
local fw_path="/usr/lib/firmware/$fw_name"
if [[ -f $fw_path ]]; then
log_ok "Firmware $fw_name already installed."
continue
fi
local basename
basename=$(basename "$fw_name")
local url="https://github.com/winterheart/broadcom-bt-firmware/raw/master/brcm/$basename"
log_warn "Missing firmware: $fw_name"
apply_fix "Downloading $basename from broadcom-bt-firmware repo" \
_download_firmware "$url" "$fw_path"
done
}
_download_firmware() {
local url="$1"
local dest="$2"
mkdir -p "$(dirname "$dest")"
wget -q "$url" -O "$dest" || curl -sL "$url" -o "$dest"
}
# ==========================================================================
# 4. Reset stuck adapter via USB reset
# ==========================================================================
check_adapter_stuck() {
echo ""
log_info "Checking if Bluetooth adapter is responsive..."
# Test if bluetoothctl can see the adapter
local adapter_list
adapter_list=$(_btctl list | grep "^Controller" || true)
if [[ -n $adapter_list ]]; then
log_ok "Adapter is responsive: $adapter_list"
return 0
fi
log_warn "Adapter not responding to bluetoothctl."
# Try USB reset if usbreset is available
local bt_usb
bt_usb=$(lsusb 2>/dev/null | grep -i bluetooth | head -1 || true)
if [[ -n $bt_usb ]]; then
local usb_id
usb_id=$(echo "$bt_usb" | grep -oP 'ID \K[0-9a-f]{4}:[0-9a-f]{4}')
if [[ -n $usb_id ]] && has_cmd usbreset; then
apply_fix "USB-resetting Bluetooth adapter ($usb_id)" \
usbreset "$usb_id"
else
log_info "Falling back to btusb module reload..."
apply_fix "Reloading btusb kernel module" \
_reload_btusb
fi
else
log_error "No USB Bluetooth adapter found. Is the dongle plugged in?"
fi
}
_reload_btusb() {
modprobe -r btusb && sleep 1 && modprobe btusb && sleep 2
}
# ---------------------------------------------------------------------------
# Helper: check if A2DP services are resolved for a connected device
# Returns 0 if resolved, 1 otherwise.
# ---------------------------------------------------------------------------
_services_resolved() {
local mac="$1"
local dbus_path="/org/bluez/hci0/dev_${mac//:/_}"
local result
result=$(dbus-send --system --print-reply \
--dest=org.bluez "$dbus_path" \
org.freedesktop.DBus.Properties.Get \
string:"org.bluez.Device1" string:"ServicesResolved" 2>/dev/null || true)
echo "$result" | grep -q "boolean true"
}
# ---------------------------------------------------------------------------
# Helper: full reset cycle — btusb reload + service restarts + reconnect.
# Fixes stale HCI link state ("link tx timeout" / ServicesResolved stuck).
# ---------------------------------------------------------------------------
_full_adapter_reset_and_connect() {
local mac="$1"
log_info "Performing full adapter reset (btusb reload)..."
_btctl disconnect "$mac" >/dev/null 2>&1 || true
sleep 1
modprobe -r btusb && sleep 2 && modprobe btusb && sleep 5
systemctl restart bluetooth.service
sleep 3
_restart_pipewire_stack
sleep 3
log_info "Reconnecting to $mac after adapter reset..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $mac"; sleep 20; } \
| bluetoothctl 2>/dev/null || true
}
# ---------------------------------------------------------------------------
# Helper: verify the Bluetooth audio sink appeared in PipeWire.
# ---------------------------------------------------------------------------
_verify_audio_sink() {
local mac="$1"
local card_name="bluez_card.${mac//:/_}"
if ! has_cmd pactl; then
return 0
fi
# Give PipeWire time to create the audio card
local _attempt
for _attempt in 1 2 3 4 5; do
if _run_as_user pactl list cards short 2>/dev/null | grep -q "$card_name"; then
log_ok "Bluetooth audio card detected in PipeWire."
return 0
fi
sleep 3
done
log_warn "Bluetooth audio card not found in PipeWire after connection."
return 1
}
# ==========================================================================
# 5. Remove stale pairing for target device (if specified)
# ==========================================================================
remove_stale_pairing() {
if [[ -z $TARGET_MAC ]]; then
return 0
fi
echo ""
log_info "Checking for stale pairing with $TARGET_MAC..."
local info
info=$(_btctl info "$TARGET_MAC" || true)
if echo "$info" | grep -q "Device $TARGET_MAC"; then
local paired
paired=$(echo "$info" | grep "Paired:" | awk '{print $2}')
local connected
connected=$(echo "$info" | grep "Connected:" | awk '{print $2}')
if [[ $paired == "yes" && $connected == "no" ]]; then
log_warn "Device is paired but NOT connected — may have stale pairing."
apply_fix "Removing stale pairing for $TARGET_MAC" \
_btctl remove "$TARGET_MAC"
elif [[ $paired == "no" ]]; then
log_info "Device is not currently paired."
else
log_ok "Device is paired and connected."
fi
else
log_info "Device $TARGET_MAC not found in bluetoothctl. Fresh pairing needed."
fi
}
# ==========================================================================
# 6. Restart Bluetooth service to apply changes
# ==========================================================================
restart_bluetooth() {
echo ""
if [[ $FIXES_APPLIED -gt 0 ]]; then
apply_fix "Restarting bluetooth.service to apply changes" \
systemctl restart bluetooth.service
else
log_info "No fixes applied — skipping service restart."
fi
}
# ==========================================================================
# 7. Disable USB autosuspend for Bluetooth adapter
# ==========================================================================
fix_usb_autosuspend() {
echo ""
log_info "Checking USB autosuspend for Bluetooth adapter..."
local bt_usb
bt_usb=$(lsusb 2>/dev/null | grep -i bluetooth | head -1 || true)
if [[ -z $bt_usb ]]; then
return 0
fi
local usb_id
usb_id=$(echo "$bt_usb" | grep -oP 'ID \K[0-9a-f]{4}:[0-9a-f]{4}' || true)
if [[ -z $usb_id ]]; then
return 0
fi
local vendor="${usb_id%%:*}"
local product="${usb_id##*:}"
# Find the sysfs device path
local sysfs_path=""
local dev_path
for dev_path in /sys/bus/usb/devices/*/; do
if [[ -f "${dev_path}idVendor" && -f "${dev_path}idProduct" ]]; then
local v p
v=$(cat "${dev_path}idVendor" 2>/dev/null || true)
p=$(cat "${dev_path}idProduct" 2>/dev/null || true)
if [[ $v == "$vendor" && $p == "$product" ]]; then
sysfs_path="$dev_path"
break
fi
fi
done
if [[ -z $sysfs_path ]]; then
log_warn "Could not find sysfs path for BT adapter."
return 0
fi
local power_control="${sysfs_path}power/control"
if [[ -f $power_control ]]; then
local current
current=$(cat "$power_control" 2>/dev/null || true)
if [[ $current != "on" ]]; then
log_warn "USB autosuspend is enabled ($current) — can cause audio dropouts."
apply_fix "Disabling USB autosuspend for BT adapter" \
_disable_usb_autosuspend "$power_control" "$vendor" "$product"
else
log_ok "USB autosuspend already disabled."
fi
fi
}
_disable_usb_autosuspend() {
local power_control="$1"
local vendor="$2"
local product="$3"
# Immediate fix
echo "on" > "$power_control"
# Persistent udev rule
local rule_file="/etc/udev/rules.d/50-bluetooth-no-autosuspend.rules"
local rule="ACTION==\"add\", SUBSYSTEM==\"usb\", ATTR{idVendor}==\"$vendor\", ATTR{idProduct}==\"$product\", ATTR{power/control}=\"on\""
if [[ ! -f $rule_file ]] || ! grep -qF "$vendor" "$rule_file" 2>/dev/null; then
echo "$rule" > "$rule_file"
udevadm control --reload-rules 2>/dev/null || true
log_info "Created persistent udev rule: $rule_file"
fi
}
# ==========================================================================
# 8. Check PipeWire/WirePlumber health (hung audio stack)
# ==========================================================================
check_pipewire_health() {
echo ""
log_info "Checking PipeWire/WirePlumber health..."
if ! has_cmd wpctl; then
log_info "wpctl not found — skipping PipeWire health check."
return 0
fi
# Test if PipeWire is responding within 3 seconds
if timeout 3 _run_as_user wpctl status &>/dev/null; then
log_ok "PipeWire is responsive."
return 0
fi
log_warn "PipeWire/WirePlumber appears hung (wpctl timed out)."
apply_fix "Restarting PipeWire + WirePlumber audio stack" \
_restart_pipewire_stack
}
# ---------------------------------------------------------------------------
# Helper: run a command as the actual (non-root) user with PipeWire env.
# Needed because pactl/wpctl/systemctl --user talk to the user session.
# ---------------------------------------------------------------------------
_run_as_user() {
local target_user
target_user="${SUDO_USER:-$USER}"
local target_uid
target_uid=$(id -u "$target_user")
sudo -u "$target_user" \
XDG_RUNTIME_DIR="/run/user/$target_uid" \
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$target_uid/bus" \
"$@"
}
_restart_pipewire_stack() {
_run_as_user systemctl --user restart pipewire pipewire-pulse wireplumber
sleep 3
log_info "Waiting for audio stack to initialize..."
}
# ==========================================================================
# 9. Auto-connect target device
# ==========================================================================
connect_device() {
if [[ -z $TARGET_MAC ]]; then
return 0
fi
echo ""
log_info "Attempting to connect to $TARGET_MAC..."
# Check if already connected
local info
info=$(_btctl info "$TARGET_MAC" || true)
if echo "$info" | grep -q "Connected: yes"; then
log_ok "Device $TARGET_MAC is already connected."
return 0
fi
# Power on adapter
_btctl power on >/dev/null || true
sleep 1
# ---- Attempt 1: direct connect (existing pairing) ----
if echo "$info" | grep -q "Paired: yes"; then
log_info "Device is already paired. Trying direct connect..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $TARGET_MAC"; sleep 15; } \
| bluetoothctl 2>/dev/null || true
if _check_connection_health "$TARGET_MAC"; then
return 0
fi
# Direct connect failed — remove stale pairing and try fresh
log_warn "Direct connect failed. Removing stale pairing for fresh start."
_btctl remove "$TARGET_MAC" >/dev/null || true
sleep 2
fi
# ---- Attempt 2: scan + pair from scratch ----
log_info "Scanning for $TARGET_MAC (20 seconds)..."
log_info "Make sure the device is in pairing mode."
{ echo "power on"; sleep 1; echo "scan on"; sleep 20; echo "scan off"; sleep 2; } \
| bluetoothctl 2>/dev/null || true
# Check if device was found
local devices
devices=$(_btctl devices || true)
if ! echo "$devices" | grep -qi "$TARGET_MAC"; then
log_error "Device $TARGET_MAC not found during scan."
log_info "Put the device in pairing mode and re-run the script."
return 1
fi
log_ok "Device found during scan."
# Pair
log_info "Pairing..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "pair $TARGET_MAC"; sleep 5; } \
| bluetoothctl 2>/dev/null || true
# Trust (so it auto-reconnects in the future)
log_info "Trusting..."
{ echo "trust $TARGET_MAC"; sleep 2; } | bluetoothctl 2>/dev/null || true
# Connect
log_info "Connecting..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $TARGET_MAC"; sleep 15; } \
| bluetoothctl 2>/dev/null || true
# Verify connection + services + audio
if _check_connection_health "$TARGET_MAC"; then
return 0
fi
log_error "Connection to $TARGET_MAC failed."
log_info "Try putting the device in pairing mode and re-run."
return 1
}
# ---------------------------------------------------------------------------
# Helper: verify connection is fully healthy (connected + services + audio).
# If connected but services stuck, triggers full adapter reset + retry.
# ---------------------------------------------------------------------------
_check_connection_health() {
local mac="$1"
local info
sleep 2
info=$(_btctl info "$mac" || true)
# Not connected at all
if ! echo "$info" | grep -q "Connected: yes"; then
return 1
fi
# Connected — check if A2DP services resolved
local _attempt
for _attempt in 1 2 3; do
if _services_resolved "$mac"; then
log_ok "Connected to $mac with A2DP services resolved."
_verify_audio_sink "$mac" || true
return 0
fi
sleep 3
done
# Connected but ServicesResolved stuck at false — stale HCI link state.
log_warn "Connected but A2DP services not resolved (stale HCI link state)."
apply_fix "Full adapter reset to fix stale link" \
_full_adapter_reset_and_connect "$mac"
# Verify after reset
sleep 3
if _services_resolved "$mac"; then
log_ok "Connected to $mac with A2DP services resolved after reset."
_verify_audio_sink "$mac" || true
return 0
fi
return 1
}
# ==========================================================================
# 10. Set audio profile (avoid SBC-XQ dropouts on older adapters)
# ==========================================================================
set_audio_profile() {
if [[ -z $TARGET_MAC ]]; then
return 0
fi
if ! has_cmd pactl; then
return 0
fi
echo ""
log_info "Checking audio profile..."
# Wait a moment for PipeWire to set up the audio card
sleep 3
local card_name="bluez_card.${TARGET_MAC//:/_}"
local card_info
card_info=$(_run_as_user pactl list cards 2>/dev/null || true)
if ! echo "$card_info" | grep -q "$card_name"; then
log_info "No PipeWire audio card found for device (may not be an audio device)."
return 0
fi
local current_profile
current_profile=$(echo "$card_info" | grep -A 50 "$card_name" | grep "Active Profile:" | head -1 | awk '{print $3}' || true)
if [[ $current_profile == *"sbc_xq"* ]]; then
log_warn "SBC-XQ codec active — may cause audio dropouts on older adapters."
apply_fix "Switching to standard SBC codec" \
_run_as_user pactl set-card-profile "$card_name" a2dp-sink
elif [[ -n $current_profile ]]; then
log_ok "Audio profile: $current_profile"
fi
}
# ==========================================================================
# 11. Show connection instructions
# ==========================================================================
show_instructions() {
echo ""
echo "==========================================="
echo " Next Steps"
echo "==========================================="
echo ""
echo "1. Put your Bluetooth device in PAIRING mode"
echo " (e.g., hold the Bluetooth button until LED blinks rapidly)"
echo ""
echo "2. In bluetoothctl:"
if [[ -n $TARGET_MAC ]]; then
cat <<EOF
scan on
# Wait for device to appear
pair $TARGET_MAC
trust $TARGET_MAC
connect $TARGET_MAC
EOF
else
cat <<EOF
scan on
# Wait for device to appear, note its MAC address
pair <MAC>
trust <MAC>
connect <MAC>
EOF
fi
echo ""
echo "3. If connection still fails, check logs:"
echo " journalctl -u bluetooth -f"
echo ""
}
# ==========================================================================
# 12. Dump diagnostic info
# ==========================================================================
dump_diagnostics() {
echo ""
log_info "=== Diagnostic Summary ==="
echo ""
echo "--- Bluetooth adapter ---"
_btctl show | grep -v '\[bluetoothctl\]' | head -20 || true
echo ""
echo "--- Known devices ---"
_btctl devices | grep '^Device' || true
echo ""
echo "--- Loaded Bluetooth kernel modules ---"
lsmod | grep -i bluetooth || echo "(none loaded)"
echo ""
echo "--- rfkill status ---"
rfkill list bluetooth 2>/dev/null || echo "(rfkill not available)"
if [[ -n $TARGET_MAC ]]; then
echo ""
echo "--- Device info: $TARGET_MAC ---"
_btctl info "$TARGET_MAC" || echo "(device not known)"
fi
echo ""
echo "--- Recent bluetooth journal entries ---"
journalctl -u bluetooth --no-pager -n 20 2>/dev/null || true
}
# ==========================================================================
# Main

View File

@ -145,288 +145,11 @@ fix_nm_wait_online() {
return 0
}
# ===================================================================
# Fix 2: Sysctl tuning (swappiness, VFS cache, dirty pages)
# ===================================================================
fix_sysctl_tuning() {
local sysctl_file="/etc/sysctl.d/99-performance-tuning.conf"
# shellcheck source=lib/ubuntu_perf_fixes.sh
source "$SCRIPT_DIR/lib/ubuntu_perf_fixes.sh"
# shellcheck source=lib/ubuntu_perf_more.sh
source "$SCRIPT_DIR/lib/ubuntu_perf_more.sh"
if [[ -f $sysctl_file ]]; then
log_ok "Sysctl performance tuning already applied — skipping."
return 0
fi
# Save current values for undo
local cur_swappiness cur_vfs cur_dirty_ratio cur_dirty_bg
cur_swappiness=$(sysctl -n vm.swappiness 2>/dev/null || echo 60)
cur_vfs=$(sysctl -n vm.vfs_cache_pressure 2>/dev/null || echo 100)
cur_dirty_ratio=$(sysctl -n vm.dirty_ratio 2>/dev/null || echo 20)
cur_dirty_bg=$(sysctl -n vm.dirty_background_ratio 2>/dev/null || echo 10)
cat >"$sysctl_file" <<'SYSCTL'
# Performance tuning for Ubuntu laptop with 32GB RAM + NVMe SSD
# Created by fix_ubuntu_performance.sh
#
# vm.swappiness=10: Prefer keeping data in RAM over swapping (32GB is plenty)
# vm.vfs_cache_pressure=50: Keep filesystem dentries/inodes cached longer (helps dev work)
# vm.dirty_ratio=15: Allow more dirty pages before forced writeback (NVMe handles bursts)
# vm.dirty_background_ratio=5: Start background writeback earlier for smoother I/O
vm.swappiness = 10
vm.vfs_cache_pressure = 50
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
SYSCTL
# Apply immediately
sysctl --system >/dev/null 2>&1
add_undo "# Undo: Remove sysctl tuning, restore defaults"
add_undo "rm -f /etc/sysctl.d/99-performance-tuning.conf"
add_undo "sysctl -w vm.swappiness=$cur_swappiness vm.vfs_cache_pressure=$cur_vfs vm.dirty_ratio=$cur_dirty_ratio vm.dirty_background_ratio=$cur_dirty_bg >/dev/null"
add_undo ""
return 0
}
# ===================================================================
# Fix 3: NVIDIA persistence mode via systemd service
# ===================================================================
fix_nvidia_persistence() {
local service_file="/etc/systemd/system/nvidia-persistence.service"
# Check if persistence is already on
if nvidia-smi -q 2>/dev/null | grep -q "Persistence Mode.*Enabled"; then
log_ok "NVIDIA persistence mode is already enabled — skipping."
return 0
fi
# On Ubuntu, nvidia-persistenced.service is "static" (no [Install] section)
# and starts with --no-persistence-mode. We create a small helper service
# that runs `nvidia-smi -pm 1` after the daemon is up.
local helper_svc="/etc/systemd/system/nvidia-persistence-mode.service"
if [[ -f $helper_svc ]] && systemctl is-enabled nvidia-persistence-mode.service >/dev/null 2>&1; then
# Already set up — just make sure it's active this boot
if ! nvidia-smi -q 2>/dev/null | grep -q "Persistence Mode.*Enabled"; then
systemctl start nvidia-persistence-mode.service 2>/dev/null || true
fi
log_ok "NVIDIA persistence mode helper already configured."
return 0
fi
if command -v nvidia-persistenced >/dev/null 2>&1; then
# Ensure the daemon is running
systemctl start nvidia-persistenced.service 2>/dev/null || true
# Create a proper service with [Install] that runs nvidia-smi -pm 1
cat >"$helper_svc" <<'NVSVC'
[Unit]
Description=Enable NVIDIA Persistence Mode
After=nvidia-persistenced.service
Requires=nvidia-persistenced.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/nvidia-smi -pm 1
ExecStop=/usr/bin/nvidia-smi -pm 0
[Install]
WantedBy=multi-user.target
NVSVC
systemctl daemon-reload
systemctl enable --now nvidia-persistence-mode.service
add_undo "# Undo: Remove NVIDIA persistence mode helper service"
add_undo "systemctl disable --now nvidia-persistence-mode.service 2>/dev/null || true"
add_undo "rm -f /etc/systemd/system/nvidia-persistence-mode.service"
add_undo "nvidia-smi -pm 0 2>/dev/null || true"
add_undo "systemctl daemon-reload"
add_undo ""
else
# Fall back to a simple systemd service using nvidia-smi
cat >"$service_file" <<'NVSVC'
[Unit]
Description=NVIDIA Persistence Mode
After=nvidia.target
Requires=nvidia.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/nvidia-smi -pm 1
ExecStop=/usr/bin/nvidia-smi -pm 0
[Install]
WantedBy=multi-user.target
NVSVC
systemctl daemon-reload
systemctl enable --now nvidia-persistence.service
add_undo "# Undo: Remove NVIDIA persistence service"
add_undo "systemctl disable --now nvidia-persistence.service 2>/dev/null || true"
add_undo "rm -f /etc/systemd/system/nvidia-persistence.service"
add_undo "systemctl daemon-reload"
add_undo ""
fi
return 0
}
# ===================================================================
# Fix 4: Install and enable earlyoom
# ===================================================================
fix_earlyoom() {
if systemctl is-active earlyoom.service >/dev/null 2>&1; then
log_ok "earlyoom is already running — skipping."
return 0
fi
if ! dpkg -l earlyoom 2>/dev/null | grep -q '^ii'; then
log_info "Installing earlyoom..."
apt-get install -y earlyoom >/dev/null 2>&1
fi
# Configure earlyoom: kill at 5% free RAM / 10% free swap
local earlyoom_conf="/etc/default/earlyoom"
if [[ -f $earlyoom_conf ]]; then
cp "$earlyoom_conf" "${earlyoom_conf}.bak"
fi
cat >"$earlyoom_conf" <<'EARLYOOM'
# earlyoom configuration - prevent OOM hard-freezes
# Created by fix_ubuntu_performance.sh
# -r 5 = act when free RAM drops below 5%
# -s 10 = act when free swap drops below 10%
# -n = send SIGTERM first (graceful), then SIGKILL
# --prefer="(firefox|chromium|chrome)" = prefer killing browsers (they recover well)
EARLYOOM_ARGS="-r 5 -s 10 -n --prefer '(firefox|chromium|chrome)'"
EARLYOOM
systemctl enable --now earlyoom.service
add_undo "# Undo: Disable and remove earlyoom"
add_undo "systemctl disable --now earlyoom.service 2>/dev/null || true"
add_undo "apt-get remove -y earlyoom >/dev/null 2>&1 || true"
add_undo ""
return 0
}
# ===================================================================
# Fix 5: Mask failed SSSD units (not needed on non-domain laptops)
# ===================================================================
fix_failed_sssd() {
local sssd_units=(
sssd-pac.service
sssd-nss.socket
sssd-pac.socket
sssd-pam-priv.socket
sssd-pam.socket
)
local any_failed=false
for unit in "${sssd_units[@]}"; do
if systemctl is-failed "$unit" >/dev/null 2>&1; then
any_failed=true
break
fi
done
if [[ $any_failed == "false" ]]; then
log_ok "No failed SSSD units — skipping."
return 0
fi
add_undo "# Undo: Unmask SSSD units"
for unit in "${sssd_units[@]}"; do
if systemctl is-failed "$unit" >/dev/null 2>&1; then
systemctl stop "$unit" 2>/dev/null || true
systemctl mask "$unit"
log_info "Masked $unit"
add_undo "systemctl unmask $unit"
fi
done
systemctl reset-failed 2>/dev/null || true
add_undo ""
return 0
}
# ===================================================================
# Fix 6: Journal vacuum + permanent size cap
# ===================================================================
fix_journal() {
# 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 — skipping."
return 0
fi
mkdir -p "$dropin_dir"
cat >"$dropin_file" <<'JOURNALEOF'
[Journal]
SystemMaxUse=300M
JOURNALEOF
# Vacuum existing logs
journalctl --vacuum-size=300M 2>/dev/null || true
systemctl restart systemd-journald
add_undo "# Undo: Remove journal size cap"
add_undo "rm -f /etc/systemd/journald.conf.d/size-limit.conf"
add_undo "systemctl restart systemd-journald"
add_undo ""
return 0
}
# ===================================================================
# Fix 7: Disable snap-related boot slowness (optional but impactful)
# ===================================================================
fix_snap_startup() {
# Disable snapd.snap-repair.timer - not critical, runs periodically
if systemctl is-enabled snapd.snap-repair.timer >/dev/null 2>&1; then
systemctl disable snapd.snap-repair.timer
systemctl stop snapd.snap-repair.timer 2>/dev/null || true
add_undo "# Undo: Re-enable snap repair timer"
add_undo "systemctl enable snapd.snap-repair.timer"
add_undo ""
else
log_ok "snapd.snap-repair.timer already disabled — skipping."
fi
return 0
}
# ===================================================================
# Undo mode: run the most recent undo script
# ===================================================================
run_undo() {
local latest_undo
# shellcheck disable=SC2012
latest_undo=$(ls -1t /root/undo_ubuntu_performance_*.sh 2>/dev/null | head -1)
if [[ -z ${latest_undo:-} ]]; then
log_error "No undo script found in /root/"
exit 1
fi
log_info "Running undo script: $latest_undo"
bash "$latest_undo"
log_ok "All changes reversed."
log_info "Reboot recommended to ensure all changes take effect."
exit 0
}
# ===================================================================
# Apply all fixes
# ===================================================================
main() {
if [[ $UNDO_MODE == "true" ]]; then
run_undo

View File

@ -0,0 +1,150 @@
#!/bin/bash
# Firmware download and stuck-adapter recovery.
#
# Sourced by fix_bluetooth.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.
# ==========================================================================
# 3. Check for missing Broadcom firmware
# ==========================================================================
check_firmware() {
echo ""
log_info "Checking for missing Bluetooth firmware..."
local missing_fw
missing_fw=$(dmesg 2>/dev/null | grep -o "brcm/BCM[^ ']*\.hcd" | sort -u || true)
if [[ -z $missing_fw ]]; then
log_ok "No missing firmware detected in dmesg."
return 0
fi
local fw_name
for fw_name in $missing_fw; do
local fw_path="/usr/lib/firmware/$fw_name"
if [[ -f $fw_path ]]; then
log_ok "Firmware $fw_name already installed."
continue
fi
local basename
basename=$(basename "$fw_name")
local url="https://github.com/winterheart/broadcom-bt-firmware/raw/master/brcm/$basename"
log_warn "Missing firmware: $fw_name"
apply_fix "Downloading $basename from broadcom-bt-firmware repo" \
_download_firmware "$url" "$fw_path"
done
}
_download_firmware() {
local url="$1"
local dest="$2"
mkdir -p "$(dirname "$dest")"
wget -q "$url" -O "$dest" || curl -sL "$url" -o "$dest"
}
# ==========================================================================
# 4. Reset stuck adapter via USB reset
# ==========================================================================
check_adapter_stuck() {
echo ""
log_info "Checking if Bluetooth adapter is responsive..."
# Test if bluetoothctl can see the adapter
local adapter_list
adapter_list=$(_btctl list | grep "^Controller" || true)
if [[ -n $adapter_list ]]; then
log_ok "Adapter is responsive: $adapter_list"
return 0
fi
log_warn "Adapter not responding to bluetoothctl."
# Try USB reset if usbreset is available
local bt_usb
bt_usb=$(lsusb 2>/dev/null | grep -i bluetooth | head -1 || true)
if [[ -n $bt_usb ]]; then
local usb_id
usb_id=$(echo "$bt_usb" | grep -oP 'ID \K[0-9a-f]{4}:[0-9a-f]{4}')
if [[ -n $usb_id ]] && has_cmd usbreset; then
apply_fix "USB-resetting Bluetooth adapter ($usb_id)" \
usbreset "$usb_id"
else
log_info "Falling back to btusb module reload..."
apply_fix "Reloading btusb kernel module" \
_reload_btusb
fi
else
log_error "No USB Bluetooth adapter found. Is the dongle plugged in?"
fi
}
_reload_btusb() {
modprobe -r btusb && sleep 1 && modprobe btusb && sleep 2
}
# ---------------------------------------------------------------------------
# Helper: check if A2DP services are resolved for a connected device
# Returns 0 if resolved, 1 otherwise.
# ---------------------------------------------------------------------------
_services_resolved() {
local mac="$1"
local dbus_path="/org/bluez/hci0/dev_${mac//:/_}"
local result
result=$(dbus-send --system --print-reply \
--dest=org.bluez "$dbus_path" \
org.freedesktop.DBus.Properties.Get \
string:"org.bluez.Device1" string:"ServicesResolved" 2>/dev/null || true)
echo "$result" | grep -q "boolean true"
}
# ---------------------------------------------------------------------------
# Helper: full reset cycle — btusb reload + service restarts + reconnect.
# Fixes stale HCI link state ("link tx timeout" / ServicesResolved stuck).
# ---------------------------------------------------------------------------
_full_adapter_reset_and_connect() {
local mac="$1"
log_info "Performing full adapter reset (btusb reload)..."
_btctl disconnect "$mac" >/dev/null 2>&1 || true
sleep 1
modprobe -r btusb && sleep 2 && modprobe btusb && sleep 5
systemctl restart bluetooth.service
sleep 3
_restart_pipewire_stack
sleep 3
log_info "Reconnecting to $mac after adapter reset..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $mac"; sleep 20; } \
| bluetoothctl 2>/dev/null || true
}
# ---------------------------------------------------------------------------
# Helper: verify the Bluetooth audio sink appeared in PipeWire.
# ---------------------------------------------------------------------------
_verify_audio_sink() {
local mac="$1"
local card_name="bluez_card.${mac//:/_}"
if ! has_cmd pactl; then
return 0
fi
# Give PipeWire time to create the audio card
local _attempt
for _attempt in 1 2 3 4 5; do
if _run_as_user pactl list cards short 2>/dev/null | grep -q "$card_name"; then
log_ok "Bluetooth audio card detected in PipeWire."
return 0
fi
sleep 3
done
log_warn "Bluetooth audio card not found in PipeWire after connection."
return 1
}

View File

@ -0,0 +1,214 @@
#!/bin/bash
# PipeWire health, device connection and audio profile.
#
# Sourced by fix_bluetooth.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.
# ==========================================================================
# 8. Check PipeWire/WirePlumber health (hung audio stack)
# ==========================================================================
check_pipewire_health() {
echo ""
log_info "Checking PipeWire/WirePlumber health..."
if ! has_cmd wpctl; then
log_info "wpctl not found — skipping PipeWire health check."
return 0
fi
# Test if PipeWire is responding within 3 seconds
if timeout 3 _run_as_user wpctl status &>/dev/null; then
log_ok "PipeWire is responsive."
return 0
fi
log_warn "PipeWire/WirePlumber appears hung (wpctl timed out)."
apply_fix "Restarting PipeWire + WirePlumber audio stack" \
_restart_pipewire_stack
}
# ---------------------------------------------------------------------------
# Helper: run a command as the actual (non-root) user with PipeWire env.
# Needed because pactl/wpctl/systemctl --user talk to the user session.
# ---------------------------------------------------------------------------
_run_as_user() {
local target_user
target_user="${SUDO_USER:-$USER}"
local target_uid
target_uid=$(id -u "$target_user")
sudo -u "$target_user" \
XDG_RUNTIME_DIR="/run/user/$target_uid" \
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$target_uid/bus" \
"$@"
}
_restart_pipewire_stack() {
_run_as_user systemctl --user restart pipewire pipewire-pulse wireplumber
sleep 3
log_info "Waiting for audio stack to initialize..."
}
# ==========================================================================
# 9. Auto-connect target device
# ==========================================================================
connect_device() {
if [[ -z $TARGET_MAC ]]; then
return 0
fi
echo ""
log_info "Attempting to connect to $TARGET_MAC..."
# Check if already connected
local info
info=$(_btctl info "$TARGET_MAC" || true)
if echo "$info" | grep -q "Connected: yes"; then
log_ok "Device $TARGET_MAC is already connected."
return 0
fi
# Power on adapter
_btctl power on >/dev/null || true
sleep 1
# ---- Attempt 1: direct connect (existing pairing) ----
if echo "$info" | grep -q "Paired: yes"; then
log_info "Device is already paired. Trying direct connect..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $TARGET_MAC"; sleep 15; } \
| bluetoothctl 2>/dev/null || true
if _check_connection_health "$TARGET_MAC"; then
return 0
fi
# Direct connect failed — remove stale pairing and try fresh
log_warn "Direct connect failed. Removing stale pairing for fresh start."
_btctl remove "$TARGET_MAC" >/dev/null || true
sleep 2
fi
# ---- Attempt 2: scan + pair from scratch ----
log_info "Scanning for $TARGET_MAC (20 seconds)..."
log_info "Make sure the device is in pairing mode."
{ echo "power on"; sleep 1; echo "scan on"; sleep 20; echo "scan off"; sleep 2; } \
| bluetoothctl 2>/dev/null || true
# Check if device was found
local devices
devices=$(_btctl devices || true)
if ! echo "$devices" | grep -qi "$TARGET_MAC"; then
log_error "Device $TARGET_MAC not found during scan."
log_info "Put the device in pairing mode and re-run the script."
return 1
fi
log_ok "Device found during scan."
# Pair
log_info "Pairing..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "pair $TARGET_MAC"; sleep 5; } \
| bluetoothctl 2>/dev/null || true
# Trust (so it auto-reconnects in the future)
log_info "Trusting..."
{ echo "trust $TARGET_MAC"; sleep 2; } | bluetoothctl 2>/dev/null || true
# Connect
log_info "Connecting..."
{ echo "agent on"; echo "default-agent"; sleep 1; echo "power on"; sleep 1; echo "connect $TARGET_MAC"; sleep 15; } \
| bluetoothctl 2>/dev/null || true
# Verify connection + services + audio
if _check_connection_health "$TARGET_MAC"; then
return 0
fi
log_error "Connection to $TARGET_MAC failed."
log_info "Try putting the device in pairing mode and re-run."
return 1
}
# ---------------------------------------------------------------------------
# Helper: verify connection is fully healthy (connected + services + audio).
# If connected but services stuck, triggers full adapter reset + retry.
# ---------------------------------------------------------------------------
_check_connection_health() {
local mac="$1"
local info
sleep 2
info=$(_btctl info "$mac" || true)
# Not connected at all
if ! echo "$info" | grep -q "Connected: yes"; then
return 1
fi
# Connected — check if A2DP services resolved
local _attempt
for _attempt in 1 2 3; do
if _services_resolved "$mac"; then
log_ok "Connected to $mac with A2DP services resolved."
_verify_audio_sink "$mac" || true
return 0
fi
sleep 3
done
# Connected but ServicesResolved stuck at false — stale HCI link state.
log_warn "Connected but A2DP services not resolved (stale HCI link state)."
apply_fix "Full adapter reset to fix stale link" \
_full_adapter_reset_and_connect "$mac"
# Verify after reset
sleep 3
if _services_resolved "$mac"; then
log_ok "Connected to $mac with A2DP services resolved after reset."
_verify_audio_sink "$mac" || true
return 0
fi
return 1
}
# ==========================================================================
# 10. Set audio profile (avoid SBC-XQ dropouts on older adapters)
# ==========================================================================
set_audio_profile() {
if [[ -z $TARGET_MAC ]]; then
return 0
fi
if ! has_cmd pactl; then
return 0
fi
echo ""
log_info "Checking audio profile..."
# Wait a moment for PipeWire to set up the audio card
sleep 3
local card_name="bluez_card.${TARGET_MAC//:/_}"
local card_info
card_info=$(_run_as_user pactl list cards 2>/dev/null || true)
if ! echo "$card_info" | grep -q "$card_name"; then
log_info "No PipeWire audio card found for device (may not be an audio device)."
return 0
fi
local current_profile
current_profile=$(echo "$card_info" | grep -A 50 "$card_name" | grep "Active Profile:" | head -1 | awk '{print $3}' || true)
if [[ $current_profile == *"sbc_xq"* ]]; then
log_warn "SBC-XQ codec active — may cause audio dropouts on older adapters."
apply_fix "Switching to standard SBC codec" \
_run_as_user pactl set-card-profile "$card_name" a2dp-sink
elif [[ -n $current_profile ]]; then
log_ok "Audio profile: $current_profile"
fi
}

View File

@ -0,0 +1,128 @@
#!/bin/bash
# Stale pairing removal, service restart and USB autosuspend.
#
# Sourced by fix_bluetooth.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.
# ==========================================================================
# 5. Remove stale pairing for target device (if specified)
# ==========================================================================
remove_stale_pairing() {
if [[ -z $TARGET_MAC ]]; then
return 0
fi
echo ""
log_info "Checking for stale pairing with $TARGET_MAC..."
local info
info=$(_btctl info "$TARGET_MAC" || true)
if echo "$info" | grep -q "Device $TARGET_MAC"; then
local paired
paired=$(echo "$info" | grep "Paired:" | awk '{print $2}')
local connected
connected=$(echo "$info" | grep "Connected:" | awk '{print $2}')
if [[ $paired == "yes" && $connected == "no" ]]; then
log_warn "Device is paired but NOT connected — may have stale pairing."
apply_fix "Removing stale pairing for $TARGET_MAC" \
_btctl remove "$TARGET_MAC"
elif [[ $paired == "no" ]]; then
log_info "Device is not currently paired."
else
log_ok "Device is paired and connected."
fi
else
log_info "Device $TARGET_MAC not found in bluetoothctl. Fresh pairing needed."
fi
}
# ==========================================================================
# 6. Restart Bluetooth service to apply changes
# ==========================================================================
restart_bluetooth() {
echo ""
if [[ $FIXES_APPLIED -gt 0 ]]; then
apply_fix "Restarting bluetooth.service to apply changes" \
systemctl restart bluetooth.service
else
log_info "No fixes applied — skipping service restart."
fi
}
# ==========================================================================
# 7. Disable USB autosuspend for Bluetooth adapter
# ==========================================================================
fix_usb_autosuspend() {
echo ""
log_info "Checking USB autosuspend for Bluetooth adapter..."
local bt_usb
bt_usb=$(lsusb 2>/dev/null | grep -i bluetooth | head -1 || true)
if [[ -z $bt_usb ]]; then
return 0
fi
local usb_id
usb_id=$(echo "$bt_usb" | grep -oP 'ID \K[0-9a-f]{4}:[0-9a-f]{4}' || true)
if [[ -z $usb_id ]]; then
return 0
fi
local vendor="${usb_id%%:*}"
local product="${usb_id##*:}"
# Find the sysfs device path
local sysfs_path=""
local dev_path
for dev_path in /sys/bus/usb/devices/*/; do
if [[ -f "${dev_path}idVendor" && -f "${dev_path}idProduct" ]]; then
local v p
v=$(cat "${dev_path}idVendor" 2>/dev/null || true)
p=$(cat "${dev_path}idProduct" 2>/dev/null || true)
if [[ $v == "$vendor" && $p == "$product" ]]; then
sysfs_path="$dev_path"
break
fi
fi
done
if [[ -z $sysfs_path ]]; then
log_warn "Could not find sysfs path for BT adapter."
return 0
fi
local power_control="${sysfs_path}power/control"
if [[ -f $power_control ]]; then
local current
current=$(cat "$power_control" 2>/dev/null || true)
if [[ $current != "on" ]]; then
log_warn "USB autosuspend is enabled ($current) — can cause audio dropouts."
apply_fix "Disabling USB autosuspend for BT adapter" \
_disable_usb_autosuspend "$power_control" "$vendor" "$product"
else
log_ok "USB autosuspend already disabled."
fi
fi
}
_disable_usb_autosuspend() {
local power_control="$1"
local vendor="$2"
local product="$3"
# Immediate fix
echo "on" > "$power_control"
# Persistent udev rule
local rule_file="/etc/udev/rules.d/50-bluetooth-no-autosuspend.rules"
local rule="ACTION==\"add\", SUBSYSTEM==\"usb\", ATTR{idVendor}==\"$vendor\", ATTR{idProduct}==\"$product\", ATTR{power/control}=\"on\""
if [[ ! -f $rule_file ]] || ! grep -qF "$vendor" "$rule_file" 2>/dev/null; then
echo "$rule" > "$rule_file"
udevadm control --reload-rules 2>/dev/null || true
log_info "Created persistent udev rule: $rule_file"
fi
}

View File

@ -0,0 +1,76 @@
#!/bin/bash
# User instructions and the diagnostics dump.
#
# Sourced by fix_bluetooth.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.
# ==========================================================================
# 11. Show connection instructions
# ==========================================================================
show_instructions() {
echo ""
echo "==========================================="
echo " Next Steps"
echo "==========================================="
echo ""
echo "1. Put your Bluetooth device in PAIRING mode"
echo " (e.g., hold the Bluetooth button until LED blinks rapidly)"
echo ""
echo "2. In bluetoothctl:"
if [[ -n $TARGET_MAC ]]; then
cat <<EOF
scan on
# Wait for device to appear
pair $TARGET_MAC
trust $TARGET_MAC
connect $TARGET_MAC
EOF
else
cat <<EOF
scan on
# Wait for device to appear, note its MAC address
pair <MAC>
trust <MAC>
connect <MAC>
EOF
fi
echo ""
echo "3. If connection still fails, check logs:"
echo " journalctl -u bluetooth -f"
echo ""
}
# ==========================================================================
# 12. Dump diagnostic info
# ==========================================================================
dump_diagnostics() {
echo ""
log_info "=== Diagnostic Summary ==="
echo ""
echo "--- Bluetooth adapter ---"
_btctl show | grep -v '\[bluetoothctl\]' | head -20 || true
echo ""
echo "--- Known devices ---"
_btctl devices | grep '^Device' || true
echo ""
echo "--- Loaded Bluetooth kernel modules ---"
lsmod | grep -i bluetooth || echo "(none loaded)"
echo ""
echo "--- rfkill status ---"
rfkill list bluetooth 2>/dev/null || echo "(rfkill not available)"
if [[ -n $TARGET_MAC ]]; then
echo ""
echo "--- Device info: $TARGET_MAC ---"
_btctl info "$TARGET_MAC" || echo "(device not known)"
fi
echo ""
echo "--- Recent bluetooth journal entries ---"
journalctl -u bluetooth --no-pager -n 20 2>/dev/null || true
}

View File

@ -0,0 +1,215 @@
#!/bin/bash
# sysctl, NVIDIA persistence and earlyoom performance fixes.
#
# Sourced by fix_ubuntu_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 2: Sysctl tuning (swappiness, VFS cache, dirty pages)
# ===================================================================
fix_sysctl_tuning() {
local sysctl_file="/etc/sysctl.d/99-performance-tuning.conf"
if [[ -f $sysctl_file ]]; then
log_ok "Sysctl performance tuning already applied — skipping."
return 0
fi
# Save current values for undo
local cur_swappiness cur_vfs cur_dirty_ratio cur_dirty_bg
cur_swappiness=$(sysctl -n vm.swappiness 2>/dev/null || echo 60)
cur_vfs=$(sysctl -n vm.vfs_cache_pressure 2>/dev/null || echo 100)
cur_dirty_ratio=$(sysctl -n vm.dirty_ratio 2>/dev/null || echo 20)
cur_dirty_bg=$(sysctl -n vm.dirty_background_ratio 2>/dev/null || echo 10)
cat >"$sysctl_file" <<'SYSCTL'
# Performance tuning for Ubuntu laptop with 32GB RAM + NVMe SSD
# Created by fix_ubuntu_performance.sh
#
# vm.swappiness=10: Prefer keeping data in RAM over swapping (32GB is plenty)
# vm.vfs_cache_pressure=50: Keep filesystem dentries/inodes cached longer (helps dev work)
# vm.dirty_ratio=15: Allow more dirty pages before forced writeback (NVMe handles bursts)
# vm.dirty_background_ratio=5: Start background writeback earlier for smoother I/O
vm.swappiness = 10
vm.vfs_cache_pressure = 50
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
SYSCTL
# Apply immediately
sysctl --system >/dev/null 2>&1
add_undo "# Undo: Remove sysctl tuning, restore defaults"
add_undo "rm -f /etc/sysctl.d/99-performance-tuning.conf"
add_undo "sysctl -w vm.swappiness=$cur_swappiness vm.vfs_cache_pressure=$cur_vfs vm.dirty_ratio=$cur_dirty_ratio vm.dirty_background_ratio=$cur_dirty_bg >/dev/null"
add_undo ""
return 0
}
# ===================================================================
# Fix 3: NVIDIA persistence mode via systemd service
# ===================================================================
fix_nvidia_persistence() {
local service_file="/etc/systemd/system/nvidia-persistence.service"
# Check if persistence is already on
if nvidia-smi -q 2>/dev/null | grep -q "Persistence Mode.*Enabled"; then
log_ok "NVIDIA persistence mode is already enabled — skipping."
return 0
fi
# On Ubuntu, nvidia-persistenced.service is "static" (no [Install] section)
# and starts with --no-persistence-mode. We create a small helper service
# that runs `nvidia-smi -pm 1` after the daemon is up.
local helper_svc="/etc/systemd/system/nvidia-persistence-mode.service"
if [[ -f $helper_svc ]] && systemctl is-enabled nvidia-persistence-mode.service >/dev/null 2>&1; then
# Already set up — just make sure it's active this boot
if ! nvidia-smi -q 2>/dev/null | grep -q "Persistence Mode.*Enabled"; then
systemctl start nvidia-persistence-mode.service 2>/dev/null || true
fi
log_ok "NVIDIA persistence mode helper already configured."
return 0
fi
if command -v nvidia-persistenced >/dev/null 2>&1; then
# Ensure the daemon is running
systemctl start nvidia-persistenced.service 2>/dev/null || true
# Create a proper service with [Install] that runs nvidia-smi -pm 1
cat >"$helper_svc" <<'NVSVC'
[Unit]
Description=Enable NVIDIA Persistence Mode
After=nvidia-persistenced.service
Requires=nvidia-persistenced.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/nvidia-smi -pm 1
ExecStop=/usr/bin/nvidia-smi -pm 0
[Install]
WantedBy=multi-user.target
NVSVC
systemctl daemon-reload
systemctl enable --now nvidia-persistence-mode.service
add_undo "# Undo: Remove NVIDIA persistence mode helper service"
add_undo "systemctl disable --now nvidia-persistence-mode.service 2>/dev/null || true"
add_undo "rm -f /etc/systemd/system/nvidia-persistence-mode.service"
add_undo "nvidia-smi -pm 0 2>/dev/null || true"
add_undo "systemctl daemon-reload"
add_undo ""
else
# Fall back to a simple systemd service using nvidia-smi
cat >"$service_file" <<'NVSVC'
[Unit]
Description=NVIDIA Persistence Mode
After=nvidia.target
Requires=nvidia.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/nvidia-smi -pm 1
ExecStop=/usr/bin/nvidia-smi -pm 0
[Install]
WantedBy=multi-user.target
NVSVC
systemctl daemon-reload
systemctl enable --now nvidia-persistence.service
add_undo "# Undo: Remove NVIDIA persistence service"
add_undo "systemctl disable --now nvidia-persistence.service 2>/dev/null || true"
add_undo "rm -f /etc/systemd/system/nvidia-persistence.service"
add_undo "systemctl daemon-reload"
add_undo ""
fi
return 0
}
# ===================================================================
# Fix 4: Install and enable earlyoom
# ===================================================================
fix_earlyoom() {
if systemctl is-active earlyoom.service >/dev/null 2>&1; then
log_ok "earlyoom is already running — skipping."
return 0
fi
if ! dpkg -l earlyoom 2>/dev/null | grep -q '^ii'; then
log_info "Installing earlyoom..."
apt-get install -y earlyoom >/dev/null 2>&1
fi
# Configure earlyoom: kill at 5% free RAM / 10% free swap
local earlyoom_conf="/etc/default/earlyoom"
if [[ -f $earlyoom_conf ]]; then
cp "$earlyoom_conf" "${earlyoom_conf}.bak"
fi
cat >"$earlyoom_conf" <<'EARLYOOM'
# earlyoom configuration - prevent OOM hard-freezes
# Created by fix_ubuntu_performance.sh
# -r 5 = act when free RAM drops below 5%
# -s 10 = act when free swap drops below 10%
# -n = send SIGTERM first (graceful), then SIGKILL
# --prefer="(firefox|chromium|chrome)" = prefer killing browsers (they recover well)
EARLYOOM_ARGS="-r 5 -s 10 -n --prefer '(firefox|chromium|chrome)'"
EARLYOOM
systemctl enable --now earlyoom.service
add_undo "# Undo: Disable and remove earlyoom"
add_undo "systemctl disable --now earlyoom.service 2>/dev/null || true"
add_undo "apt-get remove -y earlyoom >/dev/null 2>&1 || true"
add_undo ""
return 0
}
# ===================================================================
# Fix 5: Mask failed SSSD units (not needed on non-domain laptops)
# ===================================================================
fix_failed_sssd() {
local sssd_units=(
sssd-pac.service
sssd-nss.socket
sssd-pac.socket
sssd-pam-priv.socket
sssd-pam.socket
)
local any_failed=false
for unit in "${sssd_units[@]}"; do
if systemctl is-failed "$unit" >/dev/null 2>&1; then
any_failed=true
break
fi
done
if [[ $any_failed == "false" ]]; then
log_ok "No failed SSSD units — skipping."
return 0
fi
add_undo "# Undo: Unmask SSSD units"
for unit in "${sssd_units[@]}"; do
if systemctl is-failed "$unit" >/dev/null 2>&1; then
systemctl stop "$unit" 2>/dev/null || true
systemctl mask "$unit"
log_info "Masked $unit"
add_undo "systemctl unmask $unit"
fi
done
systemctl reset-failed 2>/dev/null || true
add_undo ""
return 0
}

View File

@ -0,0 +1,80 @@
#!/bin/bash
# Journal, sssd and snap-startup performance fixes.
#
# Sourced by fix_ubuntu_performance.sh; split out to keep ubuntu_perf_fixes.sh
# under the 250-line cap. Sourced rather than run, so it inherits the
# caller's strict mode and the variables above the source line.
# ===================================================================
# Fix 6: Journal vacuum + permanent size cap
# ===================================================================
fix_journal() {
# 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 — skipping."
return 0
fi
mkdir -p "$dropin_dir"
cat >"$dropin_file" <<'JOURNALEOF'
[Journal]
SystemMaxUse=300M
JOURNALEOF
# Vacuum existing logs
journalctl --vacuum-size=300M 2>/dev/null || true
systemctl restart systemd-journald
add_undo "# Undo: Remove journal size cap"
add_undo "rm -f /etc/systemd/journald.conf.d/size-limit.conf"
add_undo "systemctl restart systemd-journald"
add_undo ""
return 0
}
# ===================================================================
# Fix 7: Disable snap-related boot slowness (optional but impactful)
# ===================================================================
fix_snap_startup() {
# Disable snapd.snap-repair.timer - not critical, runs periodically
if systemctl is-enabled snapd.snap-repair.timer >/dev/null 2>&1; then
systemctl disable snapd.snap-repair.timer
systemctl stop snapd.snap-repair.timer 2>/dev/null || true
add_undo "# Undo: Re-enable snap repair timer"
add_undo "systemctl enable snapd.snap-repair.timer"
add_undo ""
else
log_ok "snapd.snap-repair.timer already disabled — skipping."
fi
return 0
}
# ===================================================================
# Undo mode: run the most recent undo script
# ===================================================================
run_undo() {
local latest_undo
# shellcheck disable=SC2012
latest_undo=$(ls -1t /root/undo_ubuntu_performance_*.sh 2>/dev/null | head -1)
if [[ -z ${latest_undo:-} ]]; then
log_error "No undo script found in /root/"
exit 1
fi
log_info "Running undo script: $latest_undo"
bash "$latest_undo"
log_ok "All changes reversed."
log_info "Reboot recommended to ensure all changes take effect."
exit 0
}
# ===================================================================
# Apply all fixes
# ===================================================================

View File

@ -0,0 +1,29 @@
#!/bin/bash
# Media-type classification for the download sweep.
#
# Sourced by organize_downloads.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.
# Function to check if file has media extension (zero forks: bash 4 ${var,,})
is_media_file() {
local file="$1"
local extension="${file##*.}"
extension="${extension,,}"
# Check if it's an image
for ext in "${IMAGE_EXTENSIONS[@]}"; do
if [[ $extension == "$ext" ]]; then
return 0
fi
done
# Check if it's a video
for ext in "${VIDEO_EXTENSIONS[@]}"; do
if [[ $extension == "$ext" ]]; then
return 0
fi
done
return 1
}

View File

@ -0,0 +1,203 @@
#!/bin/bash
# Media discovery, archiving and the per-category moves.
#
# Sourced by organize_downloads.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.
# Function to find media files in a directory (non-recursive for home, avoid common system dirs)
find_media_files() {
local search_dir="$1"
local files=()
# Directories to exclude under Downloads
local -a EXCLUDES=(
".git" ".hg" ".svn" ".cache" "node_modules" "dist" "build" "out" "target" "coverage" "__pycache__" "venv" ".venv"
# previous staging dirs created by this script
".media_organize_" "media_organize_"
# too_big folder for oversized files
"too_big"
)
if [[ $search_dir == "$HOME_DIR" ]]; then
# For home directory, only check files directly in ~ (not subdirectories)
# Exclude common system/config directories
while IFS= read -r -d '' file; do
local basename
basename=$(basename "$file")
# Skip hidden files and common system directories
if [[ ! $basename =~ ^\. ]] && [[ -f $file ]]; then
if is_media_file "$file"; then
files+=("$file")
fi
fi
done < <(find "$search_dir" -maxdepth 1 -type f -print0 2>/dev/null)
else
# For Downloads, search recursively, pruning excluded directories
# Build prune expression
local prune_expr=()
for ex in "${EXCLUDES[@]}"; do
prune_expr+=(-name "$ex*" -o)
done
# Remove trailing -o
unset 'prune_expr[${#prune_expr[@]}-1]'
while IFS= read -r -d '' file; do
if is_media_file "$file"; then
files+=("$file")
fi
done < <(find "$search_dir" \( -type d \( "${prune_expr[@]}" \) -prune \) -o -type f -print0 2>/dev/null)
fi
printf '%s\n' "${files[@]}"
}
# Function to create timestamped zip archive
create_media_archive() {
local files=("$@")
if [[ ${#files[@]} -eq 0 ]]; then
log "No media files found to archive."
return 0
fi
# Create timestamp for archive name
local timestamp
timestamp=$(date '+%Y%m%d_%H%M%S')
local archive_name="media_archive_${timestamp}.zip"
local archive_path="$DOWNLOADS_DIR/$archive_name"
# Create temporary directory (fallback to /tmp if needed)
if ! mkdir -p "$TEMP_DIR" 2>/dev/null; then
TEMP_DIR="/tmp/media_organize_$$"
mkdir -p "$TEMP_DIR"
fi
# Ensure temp dir is cleaned up on function return; trap unsets itself after running
trap 'rm -rf "$TEMP_DIR" 2>/dev/null || true; trap - RETURN' RETURN
log "Found ${#files[@]} media files to archive."
log "Creating archive: $archive_path"
# Copy files to temp directory maintaining relative structure
local successfully_copied=()
local copy_errors=0
for file in "${files[@]}"; do
if [[ -f $file ]]; then
local relative_path=""
if [[ $file == "$DOWNLOADS_DIR"* ]]; then
relative_path="downloads/${file#"$DOWNLOADS_DIR"/}"
else
relative_path="home/${file#"$HOME_DIR"/}"
fi
local temp_file="$TEMP_DIR/$relative_path"
local temp_dir
temp_dir=$(dirname "$temp_file")
mkdir -p "$temp_dir"
# Check readability first to provide a clearer error
if [[ ! -r $file ]]; then
log "WARNING: Cannot read $file (permission denied?)"
((copy_errors++)) || true
continue
fi
# Attempt copy and capture any error for logging
local cp_err
if cp_err=$(cp -p "$file" "$temp_file" 2>&1); then
successfully_copied+=("$file")
else
# Surface the cp error so the user can see the reason
log "WARNING: Failed to copy $file -> $cp_err"
# Special hint for space issues
if echo "$cp_err" | grep -qi "No space left on device"; then
log "HINT: Not enough free space to stage files. Using $TEMP_DIR. Free up space or change TEMP_DIR."
fi
((copy_errors++)) || true
fi
fi
done
if [[ ${#successfully_copied[@]} -eq 0 ]]; then
log "ERROR: No files were successfully copied to temp directory."
rm -rf "$TEMP_DIR"
return 1
fi
if [[ $copy_errors -gt 0 ]]; then
log "WARNING: $copy_errors files failed to copy."
fi
# Create zip archive with maximum compression
log "Creating zip archive with ${#successfully_copied[@]} files..."
cd "$TEMP_DIR"
if zip -9 -r "$archive_path" . 2>&1; then
log "Successfully created archive with ${#successfully_copied[@]} files."
# Verify the zip file was actually created and is not empty
if [[ ! -f $archive_path ]]; then
log "ERROR: Archive file was not created at $archive_path"
rm -rf "$TEMP_DIR"
return 1
fi
local archive_size
archive_size=$(stat -c%s "$archive_path" 2>/dev/null || echo "0")
if [[ $archive_size -eq 0 ]]; then
log "ERROR: Archive file is empty"
rm -rf "$TEMP_DIR"
return 1
fi
# Remove original files only if zip was successful
local removed_count=0
local remove_errors=0
log "Starting to remove ${#successfully_copied[@]} original files..."
# Temporarily disable strict error handling for file removal
set +e
for file in "${successfully_copied[@]}"; do
if [[ -f $file ]]; then
if rm "$file" 2>/dev/null; then
removed_count=$((removed_count + 1))
log "Removed: $(basename "$file")"
else
remove_errors=$((remove_errors + 1))
log "ERROR: Failed to remove $(basename "$file")"
fi
else
log "WARNING: File no longer exists: $(basename "$file")"
fi
done
# Re-enable strict error handling
set -e
log "Successfully removed $removed_count original files."
if [[ $remove_errors -gt 0 ]]; then
log "WARNING: Failed to remove $remove_errors files."
fi
log "Archive size: $(du -h "$archive_path" | cut -f1)"
# Cleanup temp directory (trap will also attempt, which is safe)
rm -rf "$TEMP_DIR"
# Return success only if we removed files or there were no files to remove
if [[ $removed_count -gt 0 ]] || [[ ${#successfully_copied[@]} -eq 0 ]]; then
return 0
else
log "ERROR: Failed to remove any files after successful archive creation."
return 1
fi
else
log "ERROR: Failed to create archive. Original files preserved."
log "Zip command failed."
rm -rf "$TEMP_DIR"
return 1
fi
}
# Main execution

View File

@ -0,0 +1,59 @@
#!/bin/bash
# Size thresholds and the oversized-file moves.
#
# Sourced by organize_downloads.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.
# Function to check if file is too big for archiving
is_too_big() {
local file="$1"
local size
size=$(stat -c%s "$file" 2>/dev/null || echo "0")
[[ $size -gt $SIZE_THRESHOLD ]]
}
# Function to move oversized files to too_big directory
move_big_files() {
local files=("$@")
local moved_count=0
if [[ ${#files[@]} -eq 0 ]]; then
return 0
fi
# Create too_big directory if it doesn't exist
mkdir -p "$TOO_BIG_DIR"
log "Moving ${#files[@]} oversized files to $TOO_BIG_DIR..."
for file in "${files[@]}"; do
if [[ -f $file ]]; then
local basename
basename=$(basename "$file")
local dest="$TOO_BIG_DIR/$basename"
# Handle filename collision
if [[ -f $dest ]]; then
local timestamp
timestamp=$(date '+%Y%m%d_%H%M%S')
local name="${basename%.*}"
local ext="${basename##*.}"
if [[ $name == "$ext" ]]; then
dest="$TOO_BIG_DIR/${name}_${timestamp}"
else
dest="$TOO_BIG_DIR/${name}_${timestamp}.${ext}"
fi
fi
if mv "$file" "$dest" 2>/dev/null; then
log "Moved (too big): $(basename "$file") -> $dest"
moved_count=$((moved_count + 1))
else
log "ERROR: Failed to move $(basename "$file")"
fi
fi
done
log "Successfully moved $moved_count oversized files."
}

View File

@ -67,278 +67,14 @@ while [[ ${1:-} =~ ^- ]]; do
esac
done
# Function to check if file has media extension (zero forks: bash 4 ${var,,})
is_media_file() {
local file="$1"
local extension="${file##*.}"
extension="${extension,,}"
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/download_classify.sh
source "$SCRIPT_DIR/lib/download_classify.sh"
# shellcheck source=lib/download_sizes.sh
source "$SCRIPT_DIR/lib/download_sizes.sh"
# shellcheck source=lib/download_media.sh
source "$SCRIPT_DIR/lib/download_media.sh"
# Check if it's an image
for ext in "${IMAGE_EXTENSIONS[@]}"; do
if [[ $extension == "$ext" ]]; then
return 0
fi
done
# Check if it's a video
for ext in "${VIDEO_EXTENSIONS[@]}"; do
if [[ $extension == "$ext" ]]; then
return 0
fi
done
return 1
}
# Function to check if file is too big for archiving
is_too_big() {
local file="$1"
local size
size=$(stat -c%s "$file" 2>/dev/null || echo "0")
[[ $size -gt $SIZE_THRESHOLD ]]
}
# Function to move oversized files to too_big directory
move_big_files() {
local files=("$@")
local moved_count=0
if [[ ${#files[@]} -eq 0 ]]; then
return 0
fi
# Create too_big directory if it doesn't exist
mkdir -p "$TOO_BIG_DIR"
log "Moving ${#files[@]} oversized files to $TOO_BIG_DIR..."
for file in "${files[@]}"; do
if [[ -f $file ]]; then
local basename
basename=$(basename "$file")
local dest="$TOO_BIG_DIR/$basename"
# Handle filename collision
if [[ -f $dest ]]; then
local timestamp
timestamp=$(date '+%Y%m%d_%H%M%S')
local name="${basename%.*}"
local ext="${basename##*.}"
if [[ $name == "$ext" ]]; then
dest="$TOO_BIG_DIR/${name}_${timestamp}"
else
dest="$TOO_BIG_DIR/${name}_${timestamp}.${ext}"
fi
fi
if mv "$file" "$dest" 2>/dev/null; then
log "Moved (too big): $(basename "$file") -> $dest"
moved_count=$((moved_count + 1))
else
log "ERROR: Failed to move $(basename "$file")"
fi
fi
done
log "Successfully moved $moved_count oversized files."
}
# Function to find media files in a directory (non-recursive for home, avoid common system dirs)
find_media_files() {
local search_dir="$1"
local files=()
# Directories to exclude under Downloads
local -a EXCLUDES=(
".git" ".hg" ".svn" ".cache" "node_modules" "dist" "build" "out" "target" "coverage" "__pycache__" "venv" ".venv"
# previous staging dirs created by this script
".media_organize_" "media_organize_"
# too_big folder for oversized files
"too_big"
)
if [[ $search_dir == "$HOME_DIR" ]]; then
# For home directory, only check files directly in ~ (not subdirectories)
# Exclude common system/config directories
while IFS= read -r -d '' file; do
local basename
basename=$(basename "$file")
# Skip hidden files and common system directories
if [[ ! $basename =~ ^\. ]] && [[ -f $file ]]; then
if is_media_file "$file"; then
files+=("$file")
fi
fi
done < <(find "$search_dir" -maxdepth 1 -type f -print0 2>/dev/null)
else
# For Downloads, search recursively, pruning excluded directories
# Build prune expression
local prune_expr=()
for ex in "${EXCLUDES[@]}"; do
prune_expr+=(-name "$ex*" -o)
done
# Remove trailing -o
unset 'prune_expr[${#prune_expr[@]}-1]'
while IFS= read -r -d '' file; do
if is_media_file "$file"; then
files+=("$file")
fi
done < <(find "$search_dir" \( -type d \( "${prune_expr[@]}" \) -prune \) -o -type f -print0 2>/dev/null)
fi
printf '%s\n' "${files[@]}"
}
# Function to create timestamped zip archive
create_media_archive() {
local files=("$@")
if [[ ${#files[@]} -eq 0 ]]; then
log "No media files found to archive."
return 0
fi
# Create timestamp for archive name
local timestamp
timestamp=$(date '+%Y%m%d_%H%M%S')
local archive_name="media_archive_${timestamp}.zip"
local archive_path="$DOWNLOADS_DIR/$archive_name"
# Create temporary directory (fallback to /tmp if needed)
if ! mkdir -p "$TEMP_DIR" 2>/dev/null; then
TEMP_DIR="/tmp/media_organize_$$"
mkdir -p "$TEMP_DIR"
fi
# Ensure temp dir is cleaned up on function return; trap unsets itself after running
trap 'rm -rf "$TEMP_DIR" 2>/dev/null || true; trap - RETURN' RETURN
log "Found ${#files[@]} media files to archive."
log "Creating archive: $archive_path"
# Copy files to temp directory maintaining relative structure
local successfully_copied=()
local copy_errors=0
for file in "${files[@]}"; do
if [[ -f $file ]]; then
local relative_path=""
if [[ $file == "$DOWNLOADS_DIR"* ]]; then
relative_path="downloads/${file#"$DOWNLOADS_DIR"/}"
else
relative_path="home/${file#"$HOME_DIR"/}"
fi
local temp_file="$TEMP_DIR/$relative_path"
local temp_dir
temp_dir=$(dirname "$temp_file")
mkdir -p "$temp_dir"
# Check readability first to provide a clearer error
if [[ ! -r $file ]]; then
log "WARNING: Cannot read $file (permission denied?)"
((copy_errors++)) || true
continue
fi
# Attempt copy and capture any error for logging
local cp_err
if cp_err=$(cp -p "$file" "$temp_file" 2>&1); then
successfully_copied+=("$file")
else
# Surface the cp error so the user can see the reason
log "WARNING: Failed to copy $file -> $cp_err"
# Special hint for space issues
if echo "$cp_err" | grep -qi "No space left on device"; then
log "HINT: Not enough free space to stage files. Using $TEMP_DIR. Free up space or change TEMP_DIR."
fi
((copy_errors++)) || true
fi
fi
done
if [[ ${#successfully_copied[@]} -eq 0 ]]; then
log "ERROR: No files were successfully copied to temp directory."
rm -rf "$TEMP_DIR"
return 1
fi
if [[ $copy_errors -gt 0 ]]; then
log "WARNING: $copy_errors files failed to copy."
fi
# Create zip archive with maximum compression
log "Creating zip archive with ${#successfully_copied[@]} files..."
cd "$TEMP_DIR"
if zip -9 -r "$archive_path" . 2>&1; then
log "Successfully created archive with ${#successfully_copied[@]} files."
# Verify the zip file was actually created and is not empty
if [[ ! -f $archive_path ]]; then
log "ERROR: Archive file was not created at $archive_path"
rm -rf "$TEMP_DIR"
return 1
fi
local archive_size
archive_size=$(stat -c%s "$archive_path" 2>/dev/null || echo "0")
if [[ $archive_size -eq 0 ]]; then
log "ERROR: Archive file is empty"
rm -rf "$TEMP_DIR"
return 1
fi
# Remove original files only if zip was successful
local removed_count=0
local remove_errors=0
log "Starting to remove ${#successfully_copied[@]} original files..."
# Temporarily disable strict error handling for file removal
set +e
for file in "${successfully_copied[@]}"; do
if [[ -f $file ]]; then
if rm "$file" 2>/dev/null; then
removed_count=$((removed_count + 1))
log "Removed: $(basename "$file")"
else
remove_errors=$((remove_errors + 1))
log "ERROR: Failed to remove $(basename "$file")"
fi
else
log "WARNING: File no longer exists: $(basename "$file")"
fi
done
# Re-enable strict error handling
set -e
log "Successfully removed $removed_count original files."
if [[ $remove_errors -gt 0 ]]; then
log "WARNING: Failed to remove $remove_errors files."
fi
log "Archive size: $(du -h "$archive_path" | cut -f1)"
# Cleanup temp directory (trap will also attempt, which is safe)
rm -rf "$TEMP_DIR"
# Return success only if we removed files or there were no files to remove
if [[ $removed_count -gt 0 ]] || [[ ${#successfully_copied[@]} -eq 0 ]]; then
return 0
else
log "ERROR: Failed to remove any files after successful archive creation."
return 1
fi
else
log "ERROR: Failed to create archive. Original files preserved."
log "Zip command failed."
rm -rf "$TEMP_DIR"
return 1
fi
}
# Main execution
main() {
log "Starting media file organization..."

View File

@ -0,0 +1,66 @@
#!/usr/bin/env bash
# Verify a shell script split into lib/*.sh: syntax, lint, libs reachable.
#
# Usage: verify_shell_split.sh <script> <function> [function...]
#
# The stubbed run is the part that matters. bash -n and shellcheck both pass on
# a script whose `source` line resolves to nothing, so this mirrors the repo
# tree into a temp dir, replaces the final `main "$@"` with a probe that only
# checks the named functions are defined, and runs that. Nothing else executes,
# which is what makes it safe for installers and enforcement scripts.
#
# Across 18 splits it caught five bugs no static check did: SCRIPT_DIR computed
# from $0, a redeclared readonly SCRIPT_DIR, a source line displaced by a second
# split, and two libs sourcing a sibling. See docs/shell-split-recipes.md.
#
# Only works when the script ends in `main "$@"` or `main`. Scripts that run
# top-level statements need the by-hand checks in that doc instead.
set -euo pipefail
script="$1"
shift
required_funcs=("$@")
dir="$(dirname "$script")"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
echo "--- $(basename "$script")"
bash -n "$script" || exit 1
shellcheck -x "$script" || exit 1
for lib in "$dir"/lib/*.sh; do
[[ -e $lib ]] || continue
bash -n "$lib" || exit 1
shellcheck "$lib" || exit 1
done
dollar='$'
grep -q "source \"${dollar}SCRIPT_DIR/" "$script" || {
echo "no source line found" >&2
exit 1
}
# Mirror the repo tree so repo-relative sources (../../lib/common.sh) resolve.
repo="$(git -C "$dir" rev-parse --show-toplevel)"
rel="$(realpath --relative-to="$repo" "$script")"
mkdir -p "$tmp/$(dirname "$rel")"
cp -r "$repo/linux_configuration/scripts/lib" "$tmp/linux_configuration/scripts/" 2>/dev/null || true
cp "$script" "$tmp/$rel"
[[ -d "$dir/lib" ]] && cp -r "$dir/lib" "$tmp/$(dirname "$rel")/"
entry="$tmp/$rel"
probe='for f in'
for f in "${required_funcs[@]}"; do probe+=" $f"; done
probe+="; do declare -F \"${dollar}f\" >/dev/null || { echo \"MISSING: ${dollar}f\"; exit 1; }; done"
probe+='; echo " libs sourced, functions defined"'
python3 - "$entry" "$probe" <<'PY'
import sys
from pathlib import Path
p, probe = Path(sys.argv[1]), sys.argv[2]
out = [probe + "\n" if l.rstrip() in ('main "$@"', "main") else l
for l in p.read_text().splitlines(keepends=True)]
p.write_text("".join(out))
PY
bash "$entry"

View File

@ -6,14 +6,17 @@
## Where things stand
**142 files** over 250 lines (was 183). Everything is committed and pushed to
`main` at `4b2cd0c`; the tree is clean.
**118 files** over 250 lines (was 183). Everything is committed and pushed to
`main` at `2527fb3`; the tree is clean.
**`python_pkg/` is DONE — 50 violations → 0.** Do not reopen it. Cleared in
this order, one package per tranche, pushing after each: `brother_printer`
(15→0, suite pinned at 402), `code_tutor` (13→0, 216→217), then `android_ui`,
`app_icons`, `token_audit`, `focus_policy`, `random_jpg` (57/44/81/137/14),
then `wsg_grabber`'s six test modules (277).
**`python_pkg/` is DONE — 50 violations → 0.** Do not reopen it. Cleared one
package per tranche, pushing after each: `brother_printer` (15→0, suite pinned
at 402), `code_tutor` (13→0, 216→217), then `android_ui`, `app_icons`,
`token_audit`, `focus_policy`, `random_jpg` (57/44/81/137/14), then
`wsg_grabber`'s six test modules (277).
**`linux_configuration` is 84 → 60**, in seven batches. The pattern is settled
and scripted — read `docs/shell-split-recipes.md` before touching another one.
Earlier sessions had already done: the `~/utils` exemptions, the
`no-inline-python` hook, `CLAUDE.md`, `poker-stakes/`, and every `wsg_grabber`
@ -25,7 +28,7 @@ Earlier sessions had already done: the `~/utils` exemptions, the
| Directory | Count |
| ------------------------------------- | ------------ |
| `linux_configuration` | 84 |
| `linux_configuration` | 60 |
| `phone_focus_mode` | 13 (do LAST) |
| `kcd2_dice_solver` | 12 |
| `focus_owner` | 11 |
@ -33,9 +36,26 @@ Earlier sessions had already done: the `~/utils` exemptions, the
| `reverse_survivors` / `meta` / `docs` | 4 each |
| `.github` / `bucket_catch` | 2 each |
Within `linux_configuration` the bulk is `scripts/single_use/` (39 across
`features`/`utils`/`fixes`), then `scripts/periodic_background/` (10) and
`tests/` (4).
**Three `linux_configuration` files are deliberately left over the cap.** Each
needs a real refactor, not a line-count split — see "When to give up on a
seam" in the shell recipes doc:
- `diagnose_pacman_hook_stall.sh` (493) — its transaction runner assigns
`LAST_ELAPSED` that the caller reads and reads `PACMAN_BIN` that the caller
defines. Pass that state explicitly first.
- `clean_audio.sh` (419) — probe-result globals threaded through what would be
two libs.
- `setup_passwordless_system.sh` (374) — no `main()`, so the top-level
invocation block has to be preserved by hand.
**The pre-commit `shellcheck` hook lints each lib in isolation**, with no view
of the caller's globals. That is stricter than `shellcheck -x` on the entry
script and is the check that decides whether a seam is real — run
`pre-commit run shellcheck --files <all touched>` before believing a split.
The next easy wins are the remaining `main()`-shaped shell scripts; after
those, `kcd2_dice_solver` / `focus_owner` / `billsplit` (Dart+Kotlin, untouched
this session), and the four prose files, which carry zero execution risk.
## The seam-selection rule
@ -53,9 +73,8 @@ Do not work from a list in this file — it goes stale. Run:
bash ~/utils/scripts/check_file_length.sh --all
```
**Every count in this file is a snapshot and will be wrong by the time you read
it. Run the script.** The table above is a snapshot at `4b2cd0c`, quoted only
to tell you where the bulk sits, never to work from.
**Every count here is a snapshot and will be wrong by the time you read it.
Run the script.** The table above tells you where the bulk sits, nothing more.
**Do the source files in a package before its tests.** Proven on `wsg_grabber`
and again on all seven `python_pkg` packages: the test files then split along
@ -122,18 +141,20 @@ Plus `.github/workflows/file-length.yml` modelled on
class, what the tests pin in place, and the coverage behaviour of new sibling
modules. `python_pkg` is done, so this now matters only if a stray `.py`
turns up outside it.
- `docs/shell-split-recipes.md` — **read this before the first
- `docs/shell-split-recipes.md` — **read this before the next
`linux_configuration` split.** What replaces the pass count when there is no
test suite, the two live systemd units that point at repo paths, and the
jscpd trap on the first multi-lib commit.
test suite, which scripts escape the repo, the lib shape that satisfies both
shellcheck and the shebang hook, and six traps found the hard way. The
stubbed-run check is scripted at `meta/scripts/verify_shell_split.sh`; run it
on every split whose script ends in `main "$@"`.
Each rule in both cost a failed gate run or a revert to establish.
## Split recipes
- **Shell** — extract into `lib/*.sh` sourced by a thin entry script,
`set -euo pipefail` in each. Follow `phone_focus_mode/lib/` and
`linux_configuration/scripts/lib/common.sh`.
- **Shell** — extract into `lib/*.sh` sourced by a thin entry script. See
`docs/shell-split-recipes.md` for the lib shape; note it corrects the old
advice to repeat `set -euo pipefail` in every lib.
- **Python** — extract cohesive helpers into sibling modules; keep the public
API stable by re-exporting.
- **TS/Dart** — extract components; re-export from the original path so no