mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 16:26:17 +01:00
Compare commits
6 Commits
baeb1119d0
...
ddd3738976
| Author | SHA1 | Date | |
|---|---|---|---|
| ddd3738976 | |||
| c266b3cd42 | |||
| 79a49846b9 | |||
| f6bfdff76a | |||
| 72e1b6a8b1 | |||
| f5edebae4a |
@ -0,0 +1,21 @@
|
||||
{
|
||||
"title": "Split block_compulsive_opening.sh under the 250-line cap",
|
||||
"objective": "Bring block_compulsive_opening.sh (705 lines) under the repo-wide 250-line cap by moving its 26 functions into four sourced libs, preserving behaviour exactly, and keeping the deployed /usr/local/bin copy working — it is executed by this machine's beeper/signal/discord launcher wrappers and by a live pacman PostTransaction hook.",
|
||||
"acceptance_criteria": [
|
||||
"The entry script and all four lib/cco_*.sh files are each at most 250 lines.",
|
||||
"`help`, `status` and an unknown-command run are byte-identical to the pre-split baselines with unchanged exit codes (0, 0, 1).",
|
||||
"verify_shell_split.sh shows no -/+ pair except install_all and uninstall_all, the two functions deliberately changed to deploy and remove the libs.",
|
||||
"A line-multiset check accounts for every code line of the 705-line original.",
|
||||
"The FLAT deploy layout (entry + libs side by side, no lib/ subdir) runs: proven in a scratch directory, since /usr/local/bin cannot be written from a test.",
|
||||
"A missing lib fails closed with an actionable message rather than loading partially.",
|
||||
"shellcheck passes without -x and shfmt -w is a no-op on every file, with no suppression added.",
|
||||
"The new lib/tests suite passes and per-lib coverage is measured and recorded as a real number."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Executing install_all / uninstall_all / install_wrapper against the real system: they move /usr/bin binaries and write /etc/pacman.d/hooks.",
|
||||
"Executing kill_app or launch_with_timer: they pkill running applications.",
|
||||
"Re-deploying to /usr/local/bin. That is a separate, user-visible step; this commit leaves the working deployed monolith in place.",
|
||||
"The pre-existing `APPS[$app]: unbound variable` message on an unknown app, confirmed identical pre-split."
|
||||
],
|
||||
"verifier": "bash meta/scripts/check_file_length.sh --all; bash meta/scripts/verify_shell_split.sh HEAD <old> <old> <libs>; diff of help/status/unknown against captured baselines; a flat-layout simulation in a scratch dir including the missing-lib case; shellcheck + shfmt idempotence; lib/tests/run_all.sh and shell_coverage.sh."
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
{
|
||||
"title": "Split setup_night_lockdown.sh under the 250-line cap",
|
||||
"objective": "Bring setup_night_lockdown.sh (918 lines) under the cap by moving its top-level functions into five libs and its two quoted heredocs into verbatim payload files, while guaranteeing the two scripts it deploys to /usr/local/bin are unchanged — night-lockdown-unlock.timer is enabled and fires at 05:00.",
|
||||
"acceptance_criteria": [
|
||||
"The entry script and every lib is at most 250 lines, verified with the payloads git-tracked so the gate actually sees them.",
|
||||
"The emitted night-lockdown-enter.sh and night-lockdown-unlock.sh hash identically to the files currently deployed in /usr/local/bin, with mode 0755.",
|
||||
"verify_shell_split.sh reports additions only — no moved function's body changed.",
|
||||
"`--help` is byte-identical to the pre-split baseline and `status` differs only in live clock state.",
|
||||
"Both payloads parse as standalone scripts; shellcheck passes without -x and shfmt is a no-op, with no suppression added.",
|
||||
"install_enter_script and install_unlock_script run without an unbound variable."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Running `setup_night_lockdown.sh setup`: it masks the TTY login surface and tears down the GUI, with SSH as the only recovery path.",
|
||||
"Re-deploying to /usr/local/bin — unnecessary, since the split provably emits the same bytes already there.",
|
||||
"Splitting the 279-line enter payload: it is one generated artifact, and the user chose the .sh.in convention over splitting it."
|
||||
],
|
||||
"verifier": "sha256 of emitted artifacts vs /usr/local/bin (the decisive check); check_file_length.sh --all with payloads tracked; verify_shell_split.sh; diff of --help/status against baselines; bash -n on payloads; shellcheck + shfmt idempotence."
|
||||
}
|
||||
@ -0,0 +1,73 @@
|
||||
{
|
||||
"intent": "Bring block_compulsive_opening.sh (705 lines) under the 250-line cap by moving its 26 functions into four sourced libs, without breaking the deployed copy that this machine's beeper/signal/discord launchers and a live pacman PostTransaction hook execute on every use.",
|
||||
"scope": [
|
||||
"block_compulsive_opening.sh: 705 -> 182 lines",
|
||||
"New: lib/cco_state.sh (147), lib/cco_wrapper.sh (119), lib/cco_install.sh (238), lib/cco_report.sh (101)",
|
||||
"New: lib/tests/cco_harness.sh + lib/tests/test_cco_state.sh (21 assertions)",
|
||||
"Non-goal: executing install/uninstall/kill paths under test — they move system binaries and pkill running apps"
|
||||
],
|
||||
"changes": [
|
||||
"Moved all 26 functions into four libs by responsibility: state/timing (cco_state), the launch path (cco_wrapper), install/uninstall + pacman hook (cco_install), status/reset/usage (cco_report). Extracted with meta/scripts/extract_shell_functions.py, which walks brace-by-brace rather than slicing line ranges.",
|
||||
"DEPLOY SHAPE (user's decision): the libs are deployed FLAT beside the entry script in /usr/local/bin, not in a lib/ subdirectory. This matches the existing precedent — /usr/local/bin/pacman_lock_lib.sh and heavy_job_lock.sh are already deployed and sourced exactly that way. The entry script probes for lib/ first and falls back to its own directory, so the repo layout and the deployed layout both work from one source of truth.",
|
||||
"JUSTIFIED BODY CHANGE 1 -- install_all now copies the four libs to /usr/local/bin. Without this the deployed entry script would source libs that are not there. It runs even when the script is already at $install_path, because `rewrap-quiet` (the pacman hook) executes the DEPLOYED copy and would otherwise keep sourcing stale libs after an upstream change.",
|
||||
"JUSTIFIED BODY CHANGE 2 -- uninstall_all removes those four libs, so an uninstall does not strand orphans in /usr/local/bin.",
|
||||
"The entry script fails CLOSED on a missing lib, with an actionable message naming the re-install command. The pacman wrapper's fail-open pattern is deliberately NOT copied here: a half-loaded blocker that silently stops blocking is the exact failure this tool exists to prevent, and unlike pacman you do not need this script in order to repair it."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "bash meta/scripts/check_file_length.sh --all",
|
||||
"result": "pass",
|
||||
"evidence": "Over-cap list went from 4 files to 3. block_compulsive_opening.sh is 182 lines; the largest new lib is cco_install.sh at 238."
|
||||
},
|
||||
{
|
||||
"command": "diff of `help`, `status` and an unknown command against pre-split baselines",
|
||||
"result": "pass",
|
||||
"evidence": "All three byte-identical, exit codes 0/0/1 unchanged. Re-verified after shfmt. One apparent diff was traced to $0 echoing the invocation path when run from a different cwd, not to a code change."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/verify_shell_split.sh HEAD <old> <old> <4 libs>",
|
||||
"result": "pass",
|
||||
"evidence": "Exactly two -/+ pairs, install_all and uninstall_all — the two functions deliberately changed above. The other 24 functions moved byte-identically."
|
||||
},
|
||||
{
|
||||
"command": "python3 line-multiset check, original vs entry+libs (comments excluded)",
|
||||
"result": "pass",
|
||||
"evidence": "0 code lines from the 705-line original missing from the split."
|
||||
},
|
||||
{
|
||||
"command": "flat-layout simulation in a scratch dir (entry + 4 libs, no lib/ subdir)",
|
||||
"result": "pass",
|
||||
"evidence": "This is the shape install_all writes to /usr/local/bin. `help` and `status` both exit 0 from the flat layout. Removing one lib produces the fail-closed error naming the missing file and the re-install command, rather than a partial load."
|
||||
},
|
||||
{
|
||||
"command": "wrapper path against an unknown app, with HOME/XDG_STATE_HOME pointed at a tmpdir",
|
||||
"result": "pass",
|
||||
"evidence": "Rejects cleanly. The `APPS[$app]: unbound variable` message it emits was confirmed PRE-EXISTING by running the identical command against the pre-split original from git — byte-identical output, so not a regression introduced here. The real ~/.local/state/compulsive-block was confirmed untouched afterwards."
|
||||
},
|
||||
{
|
||||
"command": "lib/tests/run_all.sh",
|
||||
"result": "pass",
|
||||
"evidence": "21 assertions for cco_state, 0 failures (50 across the whole directory including the leechblock suites). Covers the allow/block decision in both directions, including the case that matters most: a PREVIOUS hour's stamp must not keep blocking, or an app could never be reopened."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/shell_coverage.sh <run_all.sh> cco_state.sh 0",
|
||||
"result": "measured, below 100%",
|
||||
"evidence": "MEASURED: cco_state.sh 62/66 lines = 93.94%. The only four uncovered lines are kill_app's pkill/pkill -9 pair, which must never execute in a test on this machine. cco_wrapper/cco_install/cco_report are 0%: every function in them moves system binaries, writes /etc/pacman.d/hooks or kills processes."
|
||||
},
|
||||
{
|
||||
"command": "shellcheck (no -x) + shfmt -w idempotence on all 8 files",
|
||||
"result": "pass",
|
||||
"evidence": "shellcheck rc=0, no suppressions added. shfmt is a no-op on every file. The hyphenated associative-array keys (signal-desktop, and the APPS/REAL_BINARIES/APP_TIMEOUT_MINUTES/PROCESS_MATCH maps) were already quoted and the corruption canary is clean."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The deployed /usr/local/bin copy is NOT updated by this commit. Until `sudo block_compulsive_opening.sh install` is re-run, the deployed 705-line monolith keeps running — which is safe, because it is self-contained and unchanged. The dangerous ordering would be deploying the new entry script without its libs; the fail-closed guard turns that into a loud error rather than a silently disabled blocker.",
|
||||
"install_all is not executed by any test (it moves /usr/bin binaries), so its new lib-copy block is verified by the flat-layout simulation rather than by running it. The simulation reproduces exactly what it writes.",
|
||||
"A pre-existing quirk was confirmed rather than fixed: `wrapper <unknown-app>` prints a raw `APPS[$app]: unbound variable` before its clean error. Identical pre-split; out of scope for a behaviour-preserving split."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; block_compulsive_opening.sh returns to a single 705-line file and lib/cco_*.sh disappear.",
|
||||
"The deployed copy needs no rollback — this commit never touched it.",
|
||||
"If the split HAD been deployed before rolling back, re-run `sudo block_compulsive_opening.sh install` from the reverted tree and then confirm `ls /usr/local/bin/cco_*.sh` returns nothing and a wrapped app still launches."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
{
|
||||
"intent": "Repair the Shell tests workflow, which has been red on main since 72e1b6a8: two security-hardening assertions grep block_compulsive_opening.sh for code that the 250-line-cap split moved into lib/cco_*.sh.",
|
||||
"scope": [
|
||||
"linux_configuration/tests/lib/security_apps.sh: two greps now search the entry script plus its libs",
|
||||
"Non-goal: any change to block_compulsive_opening.sh or its libs -- the code is correct; only the test's idea of where it lives was stale"
|
||||
],
|
||||
"changes": [
|
||||
"Built a compulsive_sources array from the entry script plus every lib/cco_*.sh, and pointed the 'Auto-close timer configuration exists' and 'launch_with_timer function exists' greps at that set instead of at the entry script alone.",
|
||||
"The glob means the next split of this script does not break these assertions again. Each lib is added only if it exists, so the array degrades to just the entry script if lib/ is ever absent.",
|
||||
"Kept both assertions about the FEATURE existing, which is what they were always for. Deleting them, or pinning them to a specific lib filename, would have traded a false failure for a weaker test."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "bash linux_configuration/tests/test_security_hardening.sh",
|
||||
"result": "pass",
|
||||
"evidence": "'Auto-close timer configuration exists' and 'launch_with_timer function exists' both PASS, where launch_with_timer failed before this change. 18 passed."
|
||||
},
|
||||
{
|
||||
"command": "gh run view 32489396229 --log-failed (the red CI run being fixed)",
|
||||
"result": "pass",
|
||||
"evidence": "CI's sole failure was 'launch_with_timer function exists' -- the assertion this commit repairs. Confirms the fix targets the actual break rather than a guess."
|
||||
},
|
||||
{
|
||||
"command": "Attribution check for the one remaining local failure",
|
||||
"result": "pass",
|
||||
"evidence": "'Compulsive block wrappers installed' fails on THIS MACHINE only, and is unrelated: signal-desktop and discord are installed but not wrapped, which the blocker's own `status` independently reports as 'installed (not wrapped)'. The same assertion PASSES in CI, where neither app exists. Pre-existing environmental state, not a regression from the split."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The glob makes the assertions insensitive to WHICH file holds the code. That is the intent -- they assert the feature exists -- but they would now also pass if the code were duplicated across libs.",
|
||||
"The unwrapped signal-desktop and discord on this machine remain unwrapped; this commit does not touch them. Running `sudo block-compulsive-opening.sh install` would wrap them, which is a user decision and outside this scope."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert this commit; the two greps return to searching only block_compulsive_opening.sh and Shell tests goes red again on launch_with_timer.",
|
||||
"Validate with: bash linux_configuration/tests/test_security_hardening.sh and confirm 'launch_with_timer function exists' PASSes."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
{
|
||||
"intent": "Repair the Shell tests failure introduced by the block_compulsive_opening split: test_security_hardening.sh grepped the entry script for code that the split moved into lib/cco_wrapper.sh.",
|
||||
"scope": [
|
||||
"linux_configuration/tests/lib/security_apps.sh: tests 17 and 18 now search the entry script and its libs",
|
||||
"Non-goal: test 19, which inspects this machine's live /usr/bin wrappers"
|
||||
],
|
||||
"changes": [
|
||||
"Tests 17 and 18 search block_compulsive_opening.sh plus lib/cco_*.sh instead of the entry script alone. Both assertions are about a FEATURE existing (the auto-close timeout config, and the launch_with_timer function); after the split that code sits one file over, so grepping only the entry script reported 'not found' for code that is present and working — a false failure. Searching the set restores the original intent and survives the next split.",
|
||||
"The lib list is built with a loop and an -f test rather than a bare glob, so an unmatched pattern cannot enter the array as a literal string and no shellcheck suppression is needed."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "bash linux_configuration/tests/test_security_hardening.sh",
|
||||
"result": "pass",
|
||||
"evidence": "'Auto-close timer configuration exists' and 'launch_with_timer function exists' both PASS. Passed: 18. The single remaining local failure is test 19 ('Compulsive block wrappers installed'), which inspects /usr/bin: signal-desktop and discord are not currently wrapped on this machine and beeper is not installed. That check is machine-state, was failing before this change, and is not what CI reported."
|
||||
},
|
||||
{
|
||||
"command": "gh run view 32489396229 --log-failed",
|
||||
"result": "diagnosed",
|
||||
"evidence": "CI's only failing assertion was 'launch_with_timer function exists — Not found at expected location', in the arch-tests job. It was NOT the new lib/tests discovery step, which passed."
|
||||
},
|
||||
{
|
||||
"command": "shellcheck linux_configuration/tests/lib/security_apps.sh",
|
||||
"result": "pass",
|
||||
"evidence": "rc=0, no suppression added."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The checks are still greps, so they prove the text exists rather than that the timer works. That was true before the split; broadening the search does not weaken them, and genuinely testing the launch path is the job of lib/tests/, which cannot execute it (it pkills live apps).",
|
||||
"Test 19 remains red locally until the wrappers are reinstalled on this machine. Out of scope here and unrelated to the split."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the two checks return to grepping the entry script only and will fail again while the split is in place."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
{
|
||||
"intent": "Bring setup_night_lockdown.sh (918 lines) under the 250-line cap, without changing a byte of the two scripts it deploys to /usr/local/bin — one of which is executed by night-lockdown-unlock.timer, which is enabled and fires at 05:00.",
|
||||
"scope": [
|
||||
"setup_night_lockdown.sh: 918 -> 127 lines",
|
||||
"New libs: nl_enter.sh, nl_unlock.sh, nl_units.sh (100), nl_config.sh (125), nl_commands.sh (82)",
|
||||
"New payloads: lib/payloads/night-lockdown-enter.sh.in (279), night-lockdown-unlock.sh.in (212)",
|
||||
"Non-goal: running `setup`. It masks the TTY login surface and tears down the GUI; the only recovery is SSH."
|
||||
],
|
||||
"changes": [
|
||||
"Moved the real top-level functions into five libs with extract_shell_functions.py. The apparent functions at lines 218/233/244/251/266 and 506/522/551 of the original are NOT top-level: they live inside the two big quoted heredocs and belong to the generated scripts. Each heredoc was therefore treated as one atomic unit.",
|
||||
"The two heredoc bodies became verbatim payload FILES rather than inline text. Both heredocs were quoted (<<'ENTER_EOF' / <<'UNLOCK_EOF'), so their bodies were already literal with no expansion — moving them to files is exactly equivalent, and it is what brings the libs under the cap.",
|
||||
"The payloads carry a .sh.in extension. They are deployment artifacts byte-pinned to the installed copy, not hand-edited shell source, so they sit outside the cap's scope the same way third_party/ does — decided by the user after being shown the alternative of splitting the 279-line enter payload.",
|
||||
"DEFECT FOUND AND FIXED -- $_NL_PAYLOAD_DIR was referenced by both install functions and defined nowhere, so `setup_night_lockdown.sh setup` would have died with 'unbound variable' partway through installing the lockdown. Reproduced directly. It is now defined in the same file as its use, eight lines above it: a definition placed in the entry script was silently stripped by an autoformat pass three separate times during this work, and this installer is not something that can be allowed to half-run."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "sha256sum of the emitted artifacts vs the LIVE deployed files",
|
||||
"result": "pass",
|
||||
"evidence": "THE decisive check. Running the split install_enter_script/install_unlock_script against redirected destinations emits 4baaf405ccee8824... and eafce28d826bb160..., which are byte-for-byte the current /usr/local/bin/night-lockdown-enter.sh and night-lockdown-unlock.sh. The payload files hash identically to the heredoc bodies extracted from the pre-split file, so the chain original-body == payload == emitted == deployed is closed. Modes are 0755 as before."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/check_file_length.sh --all",
|
||||
"result": "pass",
|
||||
"evidence": "Over-cap list went from 3 files to 2. Confirmed with the payloads git-tracked (git add -N), since the gate only sees tracked files — an untracked payload would have given a false pass."
|
||||
},
|
||||
{
|
||||
"command": "bash meta/scripts/verify_shell_split.sh HEAD <old> <old> <5 libs>",
|
||||
"result": "pass",
|
||||
"evidence": "Eleven additions and no -/+ pair on any name: every moved function is byte-identical."
|
||||
},
|
||||
{
|
||||
"command": "diff of `status` and `--help` against pre-split baselines",
|
||||
"result": "pass",
|
||||
"evidence": "--help byte-identical. `status` differed by one character — the countdown to the 05:00 timer ticked from '13h' to '12h' between the two runs. Live clock state, not a code change; every other line matches."
|
||||
},
|
||||
{
|
||||
"command": "bash -n on both payloads; shellcheck + shfmt on entry and libs",
|
||||
"result": "pass",
|
||||
"evidence": "Both payloads parse as standalone scripts. shellcheck rc=0 with no suppressions; shfmt -w is a no-op; the hyphenated-key canary is clean."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The deployed copies are NOT touched by this commit and remain byte-identical to what the split now produces, so the 05:00 unlock timer is unaffected whether or not `setup` is ever re-run.",
|
||||
"`setup` itself is never executed under test — it masks getty/autovt and tears down the GUI, with SSH as the only recovery. Its correctness rests on the emitted-artifact hash equality above plus the unchanged-function proof, not on a live run.",
|
||||
"The .sh.in convention is new. A future payload that is genuinely hand-edited source would inherit an exemption it should not have; the extension is the signal that a file is a verbatim deployment artifact."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; setup_night_lockdown.sh returns to one 918-line file and lib/nl_*.sh plus lib/payloads/ disappear.",
|
||||
"Nothing to undo on the live system — no deployed file was written.",
|
||||
"After rollback, re-run the emitted-artifact hash check against /usr/local/bin to confirm the reverted heredocs still produce 4baaf405... and eafce28d..."
|
||||
]
|
||||
}
|
||||
@ -9,6 +9,48 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# The phases live in four libs. They are found in TWO layouts, because this
|
||||
# script runs from both:
|
||||
#
|
||||
# repo: <here>/lib/cco_*.sh
|
||||
# deployed: /usr/local/bin/cco_*.sh (flat, beside the entry script)
|
||||
#
|
||||
# install_all copies the libs flat next to the installed entry script rather
|
||||
# than creating /usr/local/bin/lib, matching how pacman_lock_lib.sh and
|
||||
# heavy_job_lock.sh are already deployed there.
|
||||
#
|
||||
# readlink -f because /usr/bin/<app> wrappers exec this through its absolute
|
||||
# path and the installed copy may itself be reached via a symlink.
|
||||
#
|
||||
# This fails CLOSED: a missing lib aborts. The pacman fail-open pattern is
|
||||
# wrong here — a half-loaded blocker that silently stops blocking is the exact
|
||||
# failure this tool exists to prevent, and unlike pacman you do not need this
|
||||
# script to repair it.
|
||||
_CCO_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
|
||||
if [[ -d "$_CCO_DIR/lib" ]]; then
|
||||
_CCO_LIB_DIR="$_CCO_DIR/lib"
|
||||
else
|
||||
_CCO_LIB_DIR="$_CCO_DIR"
|
||||
fi
|
||||
|
||||
for _cco_lib in cco_state cco_wrapper cco_install cco_report; do
|
||||
if [[ ! -r "$_CCO_LIB_DIR/${_cco_lib}.sh" ]]; then
|
||||
echo "Error: missing library ${_cco_lib}.sh in $_CCO_LIB_DIR" >&2
|
||||
echo "The installation is incomplete; re-run: sudo $0 install" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
unset _cco_lib
|
||||
|
||||
# shellcheck source=lib/cco_state.sh
|
||||
. "$_CCO_LIB_DIR/cco_state.sh"
|
||||
# shellcheck source=lib/cco_wrapper.sh
|
||||
. "$_CCO_LIB_DIR/cco_wrapper.sh"
|
||||
# shellcheck source=lib/cco_install.sh
|
||||
. "$_CCO_LIB_DIR/cco_install.sh"
|
||||
# shellcheck source=lib/cco_report.sh
|
||||
. "$_CCO_LIB_DIR/cco_report.sh"
|
||||
|
||||
# Send desktop notification (inlined from common.sh to avoid dependency issues
|
||||
# when script is installed to /usr/local/bin)
|
||||
notify() {
|
||||
@ -79,571 +121,6 @@ declare -A PROCESS_MATCH=(
|
||||
["discord"]="$_cco_home/.config/discord/"
|
||||
)
|
||||
|
||||
# Ensure state directory exists
|
||||
ensure_state_dir() {
|
||||
mkdir -p "$STATE_DIR" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Log message with timestamp
|
||||
log_message() {
|
||||
local msg
|
||||
msg="$(printf '%(%Y-%m-%d %H:%M:%S)T' -1) - $1"
|
||||
echo "$msg" >&2
|
||||
echo "$msg" >>"$LOG_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Get current hour key (YYYY-MM-DD-HH format)
|
||||
get_hour_key() {
|
||||
printf '%(%Y-%m-%d-%H)T' -1
|
||||
}
|
||||
|
||||
# Get state file path for an app
|
||||
get_state_file() {
|
||||
local app="$1"
|
||||
echo "$STATE_DIR/${app}.lastopen"
|
||||
}
|
||||
|
||||
# Check if app was already opened this hour
|
||||
was_opened_this_hour() {
|
||||
local app="$1"
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
if [[ -f $state_file ]]; then
|
||||
local last_hour
|
||||
last_hour=$(cat "$state_file" 2>/dev/null || echo "")
|
||||
if [[ $last_hour == "$current_hour" ]]; then
|
||||
return 0 # Was opened this hour
|
||||
fi
|
||||
fi
|
||||
return 1 # Not opened this hour
|
||||
}
|
||||
|
||||
# Record app opening
|
||||
record_opening() {
|
||||
local app="$1"
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
echo "$current_hour" >"$state_file"
|
||||
log_message "ALLOWED: $app opened (first time this hour: $current_hour)"
|
||||
}
|
||||
|
||||
# Block app and notify
|
||||
block_app() {
|
||||
local app="$1"
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
log_message "BLOCKED: $app launch prevented (already opened this hour: $current_hour)"
|
||||
|
||||
# Send notification using common library
|
||||
notify "🚫 $app Blocked" "Already opened this hour. Wait until the next hour." critical 5000
|
||||
}
|
||||
|
||||
# Get real binary path for an app
|
||||
get_real_binary() {
|
||||
local app="$1"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
local real_binary="${REAL_BINARIES[$app]}"
|
||||
|
||||
# Check if wrapper is installed (original moved to .orig)
|
||||
if [[ -f "${wrapper_path}.orig" ]]; then
|
||||
# Wrapper installed, return the actual executable
|
||||
echo "$real_binary"
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Get running state file path for an app (tracks PID and start time)
|
||||
get_running_file() {
|
||||
local app="$1"
|
||||
echo "$STATE_DIR/${app}.running"
|
||||
}
|
||||
|
||||
# Clean up stale running state (process no longer running)
|
||||
# Uses process-name matching so Electron apps that fork don't appear stale.
|
||||
cleanup_stale_running_state() {
|
||||
local app="$1"
|
||||
local running_file
|
||||
running_file=$(get_running_file "$app")
|
||||
|
||||
if [[ ! -f $running_file ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Match on PROCESS_MATCH when the exec target is a launcher that exec()s away
|
||||
# (see the PROCESS_MATCH map); otherwise the exec target is the process.
|
||||
local real_binary="${PROCESS_MATCH[$app]:-${REAL_BINARIES[$app]}}"
|
||||
|
||||
# Check if any process matching the real binary is still running
|
||||
if ! is_app_running "$real_binary"; then
|
||||
log_message "CLEANUP: Stale running state for $app (no matching processes found)"
|
||||
rm -f "$running_file"
|
||||
fi
|
||||
}
|
||||
|
||||
# Check if app is running by process name (handles Electron apps that fork)
|
||||
is_app_running() {
|
||||
local real_binary="$1"
|
||||
pgrep -f "$real_binary" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Kill all processes matching the real binary path
|
||||
kill_app() {
|
||||
local real_binary="$1"
|
||||
pkill -f "$real_binary" 2>/dev/null || true
|
||||
sleep 2
|
||||
pkill -9 -f "$real_binary" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Check if auto-close is suspended for an app today
|
||||
is_autoclose_suspended() {
|
||||
local app="$1"
|
||||
local today
|
||||
today=$(printf '%(%Y-%m-%d)T' -1)
|
||||
local suspend_file="$STATE_DIR/${app}.suspend-autoclose"
|
||||
|
||||
if [[ -f $suspend_file ]]; then
|
||||
local suspend_date
|
||||
suspend_date=$(cat "$suspend_file" 2>/dev/null || echo "")
|
||||
if [[ $suspend_date == "$today" ]]; then
|
||||
return 0 # Suspended for today
|
||||
else
|
||||
# Stale suspend file, clean up
|
||||
rm -f "$suspend_file"
|
||||
fi
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# Launch app with auto-close timer
|
||||
launch_with_timer() {
|
||||
local app="$1"
|
||||
local real_binary="$2"
|
||||
shift 2
|
||||
|
||||
# $real_binary is what we EXEC; $proc_match is what we look for in the process
|
||||
# table. They are usually identical, but NOT when the exec target is a launcher
|
||||
# that exec()s away: discord's /usr/bin/discord.orig replaces itself with
|
||||
# ~/.config/discord/<app>/Discord, so matching/killing on the launcher path
|
||||
# would find nothing — the auto-close daemon would think the app exited
|
||||
# instantly and the time limit would silently never fire.
|
||||
local proc_match="${PROCESS_MATCH[$app]:-$real_binary}"
|
||||
|
||||
# Check if auto-close is suspended for today
|
||||
if is_autoclose_suspended "$app"; then
|
||||
log_message "LAUNCHED: $app (auto-close suspended for today)"
|
||||
exec "$real_binary" "$@"
|
||||
fi
|
||||
|
||||
# Use per-app timeout if set, otherwise fall back to global default
|
||||
local timeout_minutes="${APP_TIMEOUT_MINUTES[$app]:-$AUTO_CLOSE_TIMEOUT_MINUTES}"
|
||||
local warning_seconds=$(((timeout_minutes - AUTO_CLOSE_WARNING_MINUTES) * 60))
|
||||
local running_file
|
||||
running_file=$(get_running_file "$app")
|
||||
|
||||
# Launch the app in background
|
||||
"$real_binary" "$@" &
|
||||
local app_pid=$!
|
||||
|
||||
# Give Electron apps time to fork before we start polling
|
||||
sleep 2
|
||||
|
||||
# Record state (FORK-FREE: use printf %s for timestamp)
|
||||
echo "$app_pid $(printf '%(%s)T' -1)" >"$running_file"
|
||||
log_message "LAUNCHED: $app with PID $app_pid (auto-close in ${timeout_minutes}m)"
|
||||
|
||||
# Spawn the auto-close daemon in a completely detached subshell
|
||||
# Uses process-name matching so it works for Electron apps that fork on launch
|
||||
(
|
||||
# Detach from terminal
|
||||
exec </dev/null >/dev/null 2>&1
|
||||
|
||||
# Wait for warning time
|
||||
sleep "$warning_seconds"
|
||||
|
||||
# Check if still running before warning (by process name, not PID)
|
||||
if is_app_running "$proc_match"; then
|
||||
# Send warning notification
|
||||
notify-send -u critical -t 30000 "⏰ $app Closing Soon" \
|
||||
"Session will end in ${AUTO_CLOSE_WARNING_MINUTES} minutes. Save your work!" 2>/dev/null || true
|
||||
else
|
||||
# Process already exited
|
||||
rm -f "$running_file" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Wait remaining time
|
||||
sleep $((AUTO_CLOSE_WARNING_MINUTES * 60))
|
||||
|
||||
# Check if still running (by process name)
|
||||
if is_app_running "$proc_match"; then
|
||||
# Send final notification
|
||||
notify-send -u critical -t 5000 "🚫 $app Session Ended" \
|
||||
"Time's up! Closing $app now." 2>/dev/null || true
|
||||
|
||||
# Kill all matching processes (handles forked Electron children)
|
||||
kill_app "$proc_match"
|
||||
|
||||
printf '%(%Y-%m-%d %H:%M:%S)T - AUTO-CLOSED: %s after %dm\n' -1 "$app" "${timeout_minutes}" >>"$LOG_FILE" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
rm -f "$running_file" 2>/dev/null || true
|
||||
) &
|
||||
disown
|
||||
|
||||
# Wait for the app to exit by polling process name.
|
||||
# Electron apps fork immediately so waiting on $app_pid would return too soon.
|
||||
while is_app_running "$proc_match"; do
|
||||
sleep 5
|
||||
done
|
||||
|
||||
# Clean up running state
|
||||
rm -f "$running_file" 2>/dev/null || true
|
||||
|
||||
log_message "EXITED: $app"
|
||||
}
|
||||
|
||||
# Main wrapper function - called when wrapping app launches
|
||||
wrapper_main() {
|
||||
local app="$1"
|
||||
shift
|
||||
|
||||
ensure_state_dir
|
||||
|
||||
local real_binary
|
||||
if ! real_binary=$(get_real_binary "$app"); then
|
||||
log_message "ERROR: Real binary not found for $app"
|
||||
echo "Error: Real binary for $app not found. Was the installer run?" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Clean up stale running state from previous crashes
|
||||
cleanup_stale_running_state "$app"
|
||||
|
||||
if was_opened_this_hour "$app"; then
|
||||
block_app "$app"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
record_opening "$app"
|
||||
|
||||
# Launch with auto-close timer (replaces direct exec)
|
||||
launch_with_timer "$app" "$real_binary" "$@"
|
||||
}
|
||||
|
||||
# Install wrapper for a specific app
|
||||
install_wrapper() {
|
||||
local app="$1"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
local real_binary="${REAL_BINARIES[$app]}"
|
||||
|
||||
# Check if already wrapped: .orig must exist AND current file must be our wrapper
|
||||
if [[ -f "${wrapper_path}.orig" ]]; then
|
||||
if grep -q "block-compulsive-opening" "$wrapper_path" 2>/dev/null; then
|
||||
echo " ✓ $app already wrapped"
|
||||
return 0
|
||||
else
|
||||
# .orig exists but wrapper was overwritten (e.g. by package update)
|
||||
echo " ↻ $app wrapper was overwritten, re-installing..."
|
||||
rm -f "${wrapper_path}.orig"
|
||||
# Fall through to re-install
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if wrapper location exists (file or symlink)
|
||||
if [[ ! -e $wrapper_path && ! -L $wrapper_path ]]; then
|
||||
echo " ⚠ $app not installed ($wrapper_path not found)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check if real binary exists.
|
||||
# Special case: when the exec target IS this wrapper's own backup
|
||||
# ("${wrapper_path}.orig") the app has no separate system binary — the
|
||||
# launcher itself is the real thing, and the wrap below CREATES the .orig by
|
||||
# moving it aside. Requiring it to exist beforehand is a chicken-and-egg that
|
||||
# could never pass. The wrapper_path check above already proved it installed.
|
||||
if [[ $real_binary != "${wrapper_path}.orig" && ! -x $real_binary ]]; then
|
||||
echo " ⚠ $app real binary not found ($real_binary)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo " Installing wrapper for $app..."
|
||||
|
||||
# Handle symlinks: save the symlink itself, not the target
|
||||
if [[ -L $wrapper_path ]]; then
|
||||
local link_target
|
||||
link_target=$(readlink "$wrapper_path")
|
||||
echo " Saving symlink $wrapper_path -> $link_target as ${wrapper_path}.orig"
|
||||
# Remove symlink and create .orig that stores the link target info
|
||||
echo "SYMLINK:$link_target" >"${wrapper_path}.orig"
|
||||
rm "$wrapper_path"
|
||||
else
|
||||
echo " Backing up $wrapper_path -> ${wrapper_path}.orig"
|
||||
mv "$wrapper_path" "${wrapper_path}.orig"
|
||||
fi
|
||||
|
||||
echo " Creating wrapper at $wrapper_path"
|
||||
cat >"$wrapper_path" <<WRAPPER_EOF
|
||||
#!/bin/bash
|
||||
# Auto-generated wrapper for $app - blocks compulsive opening
|
||||
# Real binary: $real_binary
|
||||
# Original script: ${wrapper_path}.orig
|
||||
exec /usr/local/bin/block-compulsive-opening.sh wrapper "$app" "\$@"
|
||||
WRAPPER_EOF
|
||||
|
||||
chmod +x "$wrapper_path"
|
||||
echo " ✓ $app wrapper installed"
|
||||
}
|
||||
|
||||
# Uninstall wrapper for a specific app
|
||||
uninstall_wrapper() {
|
||||
local app="$1"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
|
||||
if [[ ! -f "${wrapper_path}.orig" ]]; then
|
||||
echo " ⚠ $app wrapper not found"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo " Removing wrapper for $app..."
|
||||
rm -f "$wrapper_path"
|
||||
|
||||
# Check if it was a symlink (stored as SYMLINK:target in .orig)
|
||||
local orig_content
|
||||
orig_content=$(cat "${wrapper_path}.orig" 2>/dev/null || echo "")
|
||||
if [[ $orig_content == SYMLINK:* ]]; then
|
||||
local link_target="${orig_content#SYMLINK:}"
|
||||
echo " Restoring symlink $wrapper_path -> $link_target"
|
||||
ln -s "$link_target" "$wrapper_path"
|
||||
rm "${wrapper_path}.orig"
|
||||
else
|
||||
echo " Restoring original file"
|
||||
mv "${wrapper_path}.orig" "$wrapper_path"
|
||||
fi
|
||||
echo " ✓ $app restored"
|
||||
}
|
||||
|
||||
# Install all wrappers
|
||||
install_all() {
|
||||
echo "Installing compulsive opening blockers..."
|
||||
echo ""
|
||||
|
||||
# Install main script to /usr/local/bin
|
||||
local script_path
|
||||
script_path="$(readlink -f "$0")"
|
||||
local install_path="/usr/local/bin/block-compulsive-opening.sh"
|
||||
|
||||
if [[ $script_path != "$install_path" ]]; then
|
||||
echo "Installing main script to $install_path..."
|
||||
cp "$script_path" "$install_path"
|
||||
chmod +x "$install_path"
|
||||
echo "✓ Main script installed"
|
||||
else
|
||||
echo "Main script already at $install_path"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Install wrappers for each app
|
||||
local installed=0
|
||||
for app in "${!APPS[@]}"; do
|
||||
if install_wrapper "$app"; then
|
||||
((installed++)) || true
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Installation complete. $installed app(s) wrapped."
|
||||
echo ""
|
||||
echo "Each app can now only be opened once per hour."
|
||||
echo "State files stored in: $STATE_DIR"
|
||||
echo "Logs stored in: $LOG_FILE"
|
||||
|
||||
# Install pacman hook to re-wrap after package updates
|
||||
install_pacman_hook
|
||||
}
|
||||
|
||||
# Install pacman hook to re-install wrappers after package updates
|
||||
install_pacman_hook() {
|
||||
local hook_dir="/etc/pacman.d/hooks"
|
||||
local hook_file="$hook_dir/95-compulsive-block-rewrap.hook"
|
||||
|
||||
echo ""
|
||||
echo "Installing pacman hook..."
|
||||
|
||||
mkdir -p "$hook_dir"
|
||||
|
||||
cat >"$hook_file" <<'HOOK_EOF'
|
||||
[Trigger]
|
||||
Operation = Upgrade
|
||||
Operation = Install
|
||||
Type = Package
|
||||
Target = beeper
|
||||
Target = signal-desktop
|
||||
Target = discord
|
||||
|
||||
[Action]
|
||||
Description = Re-installing compulsive opening blockers after package update
|
||||
When = PostTransaction
|
||||
Exec = /usr/local/bin/block-compulsive-opening.sh rewrap-quiet
|
||||
HOOK_EOF
|
||||
|
||||
chmod 644 "$hook_file"
|
||||
echo "✓ Pacman hook installed: $hook_file"
|
||||
echo " Wrappers will be automatically re-installed after beeper/signal/discord updates"
|
||||
}
|
||||
|
||||
# Uninstall pacman hook
|
||||
uninstall_pacman_hook() {
|
||||
local hook_file="/etc/pacman.d/hooks/95-compulsive-block-rewrap.hook"
|
||||
if [[ -f $hook_file ]]; then
|
||||
rm -f "$hook_file"
|
||||
echo "✓ Pacman hook removed"
|
||||
fi
|
||||
}
|
||||
|
||||
# Quietly re-wrap apps (for pacman hook - no interactive output)
|
||||
rewrap_quiet() {
|
||||
log_message "REWRAP: Pacman hook triggered, re-installing wrappers"
|
||||
|
||||
for app in "${!APPS[@]}"; do
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
|
||||
# Re-wrap if wrapper is missing or was overwritten by a package update
|
||||
if [[ ! -f "${wrapper_path}.orig" ]] || ! grep -q "block-compulsive-opening" "$wrapper_path" 2>/dev/null; then
|
||||
log_message "REWRAP: $app wrapper missing or overwritten, re-installing"
|
||||
rm -f "${wrapper_path}.orig"
|
||||
install_wrapper "$app" >>"$LOG_FILE" 2>&1 || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_message "REWRAP: Complete"
|
||||
}
|
||||
|
||||
# Uninstall all wrappers
|
||||
uninstall_all() {
|
||||
echo "Removing compulsive opening blockers..."
|
||||
echo ""
|
||||
|
||||
for app in "${!APPS[@]}"; do
|
||||
uninstall_wrapper "$app" || true
|
||||
done
|
||||
|
||||
rm -f "/usr/local/bin/block-compulsive-opening.sh"
|
||||
|
||||
# Remove pacman hook
|
||||
uninstall_pacman_hook
|
||||
|
||||
echo ""
|
||||
echo "Uninstallation complete."
|
||||
}
|
||||
|
||||
# Show status of all apps
|
||||
show_status() {
|
||||
ensure_state_dir
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
echo "Compulsive Opening Blocker Status"
|
||||
echo "=================================="
|
||||
echo "Current hour: $current_hour"
|
||||
echo ""
|
||||
|
||||
for app in "${!APPS[@]}"; do
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
local status="not opened this hour"
|
||||
local icon="○"
|
||||
|
||||
if [[ -f $state_file ]]; then
|
||||
local last_hour
|
||||
last_hour=$(cat "$state_file" 2>/dev/null || echo "")
|
||||
if [[ $last_hour == "$current_hour" ]]; then
|
||||
status="already opened (blocked until next hour)"
|
||||
icon="●"
|
||||
else
|
||||
status="last opened: $last_hour"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if wrapped
|
||||
local wrapped="not installed"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
if [[ -f "${wrapper_path}.orig" ]]; then
|
||||
wrapped="wrapped"
|
||||
elif [[ -f $wrapper_path ]]; then
|
||||
wrapped="installed (not wrapped)"
|
||||
fi
|
||||
|
||||
printf " %s %-15s [%s] - %s\n" "$icon" "$app" "$wrapped" "$status"
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "State directory: $STATE_DIR"
|
||||
}
|
||||
|
||||
# Reset state for an app (allow opening again)
|
||||
reset_app() {
|
||||
local app="$1"
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
|
||||
if [[ -f $state_file ]]; then
|
||||
rm -f "$state_file"
|
||||
echo "Reset $app - can be opened again this hour"
|
||||
log_message "RESET: $app state cleared by user"
|
||||
else
|
||||
echo "$app was not marked as opened"
|
||||
fi
|
||||
}
|
||||
|
||||
# Clear all state
|
||||
reset_all() {
|
||||
ensure_state_dir
|
||||
rm -f "$STATE_DIR"/*.lastopen
|
||||
echo "All apps reset - can be opened again this hour"
|
||||
log_message "RESET: All app states cleared by user"
|
||||
}
|
||||
|
||||
# Show usage
|
||||
show_usage() {
|
||||
cat <<EOF
|
||||
Block Compulsive Opening Script
|
||||
================================
|
||||
|
||||
Limits messaging apps to one launch per hour to reduce compulsive checking.
|
||||
|
||||
Usage: $0 [command] [args]
|
||||
|
||||
Commands:
|
||||
install - Install wrappers for all apps (requires root)
|
||||
uninstall - Remove all wrappers (requires root)
|
||||
status - Show current status of all apps
|
||||
reset <app> - Reset an app to allow opening again this hour
|
||||
reset-all - Reset all apps
|
||||
wrapper <app> [args] - Run as wrapper for an app (internal use)
|
||||
help - Show this help message
|
||||
|
||||
Managed Apps:
|
||||
beeper - Beeper messaging client
|
||||
signal-desktop - Signal messenger
|
||||
discord - Discord chat
|
||||
|
||||
Examples:
|
||||
sudo $0 install # Install all wrappers
|
||||
$0 status # Check which apps were opened this hour
|
||||
$0 reset discord # Allow Discord to be opened again
|
||||
|
||||
EOF
|
||||
}
|
||||
|
||||
# Main entry point
|
||||
main() {
|
||||
case "${1:-help}" in
|
||||
|
||||
@ -0,0 +1,238 @@
|
||||
#!/bin/bash
|
||||
# Install/uninstall of the per-app wrappers, the flat lib deployment and the
|
||||
# pacman rewrap hook for block_compulsive_opening.sh.
|
||||
# Sourced by the entry script; inherits its strict mode and globals.
|
||||
|
||||
# Install wrapper for a specific app
|
||||
install_wrapper() {
|
||||
local app="$1"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
local real_binary="${REAL_BINARIES[$app]}"
|
||||
|
||||
# Check if already wrapped: .orig must exist AND current file must be our wrapper
|
||||
if [[ -f "${wrapper_path}.orig" ]]; then
|
||||
if grep -q "block-compulsive-opening" "$wrapper_path" 2>/dev/null; then
|
||||
echo " ✓ $app already wrapped"
|
||||
return 0
|
||||
else
|
||||
# .orig exists but wrapper was overwritten (e.g. by package update)
|
||||
echo " ↻ $app wrapper was overwritten, re-installing..."
|
||||
rm -f "${wrapper_path}.orig"
|
||||
# Fall through to re-install
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if wrapper location exists (file or symlink)
|
||||
if [[ ! -e $wrapper_path && ! -L $wrapper_path ]]; then
|
||||
echo " ⚠ $app not installed ($wrapper_path not found)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check if real binary exists.
|
||||
# Special case: when the exec target IS this wrapper's own backup
|
||||
# ("${wrapper_path}.orig") the app has no separate system binary — the
|
||||
# launcher itself is the real thing, and the wrap below CREATES the .orig by
|
||||
# moving it aside. Requiring it to exist beforehand is a chicken-and-egg that
|
||||
# could never pass. The wrapper_path check above already proved it installed.
|
||||
if [[ $real_binary != "${wrapper_path}.orig" && ! -x $real_binary ]]; then
|
||||
echo " ⚠ $app real binary not found ($real_binary)"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo " Installing wrapper for $app..."
|
||||
|
||||
# Handle symlinks: save the symlink itself, not the target
|
||||
if [[ -L $wrapper_path ]]; then
|
||||
local link_target
|
||||
link_target=$(readlink "$wrapper_path")
|
||||
echo " Saving symlink $wrapper_path -> $link_target as ${wrapper_path}.orig"
|
||||
# Remove symlink and create .orig that stores the link target info
|
||||
echo "SYMLINK:$link_target" >"${wrapper_path}.orig"
|
||||
rm "$wrapper_path"
|
||||
else
|
||||
echo " Backing up $wrapper_path -> ${wrapper_path}.orig"
|
||||
mv "$wrapper_path" "${wrapper_path}.orig"
|
||||
fi
|
||||
|
||||
echo " Creating wrapper at $wrapper_path"
|
||||
cat >"$wrapper_path" <<WRAPPER_EOF
|
||||
#!/bin/bash
|
||||
# Auto-generated wrapper for $app - blocks compulsive opening
|
||||
# Real binary: $real_binary
|
||||
# Original script: ${wrapper_path}.orig
|
||||
exec /usr/local/bin/block-compulsive-opening.sh wrapper "$app" "\$@"
|
||||
WRAPPER_EOF
|
||||
|
||||
chmod +x "$wrapper_path"
|
||||
echo " ✓ $app wrapper installed"
|
||||
}
|
||||
|
||||
# Uninstall wrapper for a specific app
|
||||
uninstall_wrapper() {
|
||||
local app="$1"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
|
||||
if [[ ! -f "${wrapper_path}.orig" ]]; then
|
||||
echo " ⚠ $app wrapper not found"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo " Removing wrapper for $app..."
|
||||
rm -f "$wrapper_path"
|
||||
|
||||
# Check if it was a symlink (stored as SYMLINK:target in .orig)
|
||||
local orig_content
|
||||
orig_content=$(cat "${wrapper_path}.orig" 2>/dev/null || echo "")
|
||||
if [[ $orig_content == SYMLINK:* ]]; then
|
||||
local link_target="${orig_content#SYMLINK:}"
|
||||
echo " Restoring symlink $wrapper_path -> $link_target"
|
||||
ln -s "$link_target" "$wrapper_path"
|
||||
rm "${wrapper_path}.orig"
|
||||
else
|
||||
echo " Restoring original file"
|
||||
mv "${wrapper_path}.orig" "$wrapper_path"
|
||||
fi
|
||||
echo " ✓ $app restored"
|
||||
}
|
||||
|
||||
# Install all wrappers
|
||||
install_all() {
|
||||
echo "Installing compulsive opening blockers..."
|
||||
echo ""
|
||||
|
||||
# Install main script to /usr/local/bin
|
||||
local script_path
|
||||
script_path="$(readlink -f "$0")"
|
||||
local install_path="/usr/local/bin/block-compulsive-opening.sh"
|
||||
|
||||
if [[ $script_path != "$install_path" ]]; then
|
||||
echo "Installing main script to $install_path..."
|
||||
cp "$script_path" "$install_path"
|
||||
chmod +x "$install_path"
|
||||
echo "✓ Main script installed"
|
||||
else
|
||||
echo "Main script already at $install_path"
|
||||
fi
|
||||
|
||||
# The libs travel with the entry script, FLAT beside it rather than in a
|
||||
# lib/ subdirectory — the same shape as /usr/local/bin/pacman_lock_lib.sh
|
||||
# and heavy_job_lock.sh. The entry script probes for lib/ first and falls
|
||||
# back to its own directory, so both layouts work.
|
||||
#
|
||||
# This must run even when the script is already at $install_path: a lib
|
||||
# added or changed upstream still has to reach /usr/local/bin, and
|
||||
# `rewrap-quiet` from the pacman hook runs the DEPLOYED copy, which would
|
||||
# otherwise keep sourcing stale libs.
|
||||
local lib_src="$_CCO_LIB_DIR"
|
||||
local lib_dest="/usr/local/bin"
|
||||
if [[ $lib_src != "$lib_dest" ]]; then
|
||||
echo "Installing libraries to $lib_dest..."
|
||||
local lib
|
||||
for lib in cco_state cco_wrapper cco_install cco_report; do
|
||||
cp "$lib_src/${lib}.sh" "$lib_dest/${lib}.sh"
|
||||
chmod +x "$lib_dest/${lib}.sh"
|
||||
done
|
||||
echo "✓ Libraries installed"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
# Install wrappers for each app
|
||||
local installed=0
|
||||
for app in "${!APPS[@]}"; do
|
||||
if install_wrapper "$app"; then
|
||||
((installed++)) || true
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Installation complete. $installed app(s) wrapped."
|
||||
echo ""
|
||||
echo "Each app can now only be opened once per hour."
|
||||
echo "State files stored in: $STATE_DIR"
|
||||
echo "Logs stored in: $LOG_FILE"
|
||||
|
||||
# Install pacman hook to re-wrap after package updates
|
||||
install_pacman_hook
|
||||
}
|
||||
|
||||
# Install pacman hook to re-install wrappers after package updates
|
||||
install_pacman_hook() {
|
||||
local hook_dir="/etc/pacman.d/hooks"
|
||||
local hook_file="$hook_dir/95-compulsive-block-rewrap.hook"
|
||||
|
||||
echo ""
|
||||
echo "Installing pacman hook..."
|
||||
|
||||
mkdir -p "$hook_dir"
|
||||
|
||||
cat >"$hook_file" <<'HOOK_EOF'
|
||||
[Trigger]
|
||||
Operation = Upgrade
|
||||
Operation = Install
|
||||
Type = Package
|
||||
Target = beeper
|
||||
Target = signal-desktop
|
||||
Target = discord
|
||||
|
||||
[Action]
|
||||
Description = Re-installing compulsive opening blockers after package update
|
||||
When = PostTransaction
|
||||
Exec = /usr/local/bin/block-compulsive-opening.sh rewrap-quiet
|
||||
HOOK_EOF
|
||||
|
||||
chmod 644 "$hook_file"
|
||||
echo "✓ Pacman hook installed: $hook_file"
|
||||
echo " Wrappers will be automatically re-installed after beeper/signal/discord updates"
|
||||
}
|
||||
|
||||
# Uninstall pacman hook
|
||||
uninstall_pacman_hook() {
|
||||
local hook_file="/etc/pacman.d/hooks/95-compulsive-block-rewrap.hook"
|
||||
if [[ -f $hook_file ]]; then
|
||||
rm -f "$hook_file"
|
||||
echo "✓ Pacman hook removed"
|
||||
fi
|
||||
}
|
||||
|
||||
# Quietly re-wrap apps (for pacman hook - no interactive output)
|
||||
rewrap_quiet() {
|
||||
log_message "REWRAP: Pacman hook triggered, re-installing wrappers"
|
||||
|
||||
for app in "${!APPS[@]}"; do
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
|
||||
# Re-wrap if wrapper is missing or was overwritten by a package update
|
||||
if [[ ! -f "${wrapper_path}.orig" ]] || ! grep -q "block-compulsive-opening" "$wrapper_path" 2>/dev/null; then
|
||||
log_message "REWRAP: $app wrapper missing or overwritten, re-installing"
|
||||
rm -f "${wrapper_path}.orig"
|
||||
install_wrapper "$app" >>"$LOG_FILE" 2>&1 || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_message "REWRAP: Complete"
|
||||
}
|
||||
|
||||
# Uninstall all wrappers
|
||||
uninstall_all() {
|
||||
echo "Removing compulsive opening blockers..."
|
||||
echo ""
|
||||
|
||||
for app in "${!APPS[@]}"; do
|
||||
uninstall_wrapper "$app" || true
|
||||
done
|
||||
|
||||
rm -f "/usr/local/bin/block-compulsive-opening.sh"
|
||||
|
||||
# The libs install_all copied flat beside the entry script go with it;
|
||||
# leaving them behind would strand four orphans in /usr/local/bin.
|
||||
local lib
|
||||
for lib in cco_state cco_wrapper cco_install cco_report; do
|
||||
rm -f "/usr/local/bin/${lib}.sh"
|
||||
done
|
||||
|
||||
# Remove pacman hook
|
||||
uninstall_pacman_hook
|
||||
|
||||
echo ""
|
||||
echo "Uninstallation complete."
|
||||
}
|
||||
@ -0,0 +1,102 @@
|
||||
#!/bin/bash
|
||||
# Status reporting and reset commands for block_compulsive_opening.sh.
|
||||
# Sourced by the entry script; inherits its strict mode and globals.
|
||||
|
||||
# Show status of all apps
|
||||
show_status() {
|
||||
ensure_state_dir
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
echo "Compulsive Opening Blocker Status"
|
||||
echo "=================================="
|
||||
echo "Current hour: $current_hour"
|
||||
echo ""
|
||||
|
||||
for app in "${!APPS[@]}"; do
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
local status="not opened this hour"
|
||||
local icon="○"
|
||||
|
||||
if [[ -f $state_file ]]; then
|
||||
local last_hour
|
||||
last_hour=$(cat "$state_file" 2>/dev/null || echo "")
|
||||
if [[ $last_hour == "$current_hour" ]]; then
|
||||
status="already opened (blocked until next hour)"
|
||||
icon="●"
|
||||
else
|
||||
status="last opened: $last_hour"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check if wrapped
|
||||
local wrapped="not installed"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
if [[ -f "${wrapper_path}.orig" ]]; then
|
||||
wrapped="wrapped"
|
||||
elif [[ -f $wrapper_path ]]; then
|
||||
wrapped="installed (not wrapped)"
|
||||
fi
|
||||
|
||||
printf " %s %-15s [%s] - %s\n" "$icon" "$app" "$wrapped" "$status"
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "State directory: $STATE_DIR"
|
||||
}
|
||||
|
||||
# Reset state for an app (allow opening again)
|
||||
reset_app() {
|
||||
local app="$1"
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
|
||||
if [[ -f $state_file ]]; then
|
||||
rm -f "$state_file"
|
||||
echo "Reset $app - can be opened again this hour"
|
||||
log_message "RESET: $app state cleared by user"
|
||||
else
|
||||
echo "$app was not marked as opened"
|
||||
fi
|
||||
}
|
||||
|
||||
# Clear all state
|
||||
reset_all() {
|
||||
ensure_state_dir
|
||||
rm -f "$STATE_DIR"/*.lastopen
|
||||
echo "All apps reset - can be opened again this hour"
|
||||
log_message "RESET: All app states cleared by user"
|
||||
}
|
||||
|
||||
# Show usage
|
||||
show_usage() {
|
||||
cat <<EOF
|
||||
Block Compulsive Opening Script
|
||||
================================
|
||||
|
||||
Limits messaging apps to one launch per hour to reduce compulsive checking.
|
||||
|
||||
Usage: $0 [command] [args]
|
||||
|
||||
Commands:
|
||||
install - Install wrappers for all apps (requires root)
|
||||
uninstall - Remove all wrappers (requires root)
|
||||
status - Show current status of all apps
|
||||
reset <app> - Reset an app to allow opening again this hour
|
||||
reset-all - Reset all apps
|
||||
wrapper <app> [args] - Run as wrapper for an app (internal use)
|
||||
help - Show this help message
|
||||
|
||||
Managed Apps:
|
||||
beeper - Beeper messaging client
|
||||
signal-desktop - Signal messenger
|
||||
discord - Discord chat
|
||||
|
||||
Examples:
|
||||
sudo $0 install # Install all wrappers
|
||||
$0 status # Check which apps were opened this hour
|
||||
$0 reset discord # Allow Discord to be opened again
|
||||
|
||||
EOF
|
||||
}
|
||||
@ -0,0 +1,149 @@
|
||||
#!/bin/bash
|
||||
# State, timing and process helpers for block_compulsive_opening.sh.
|
||||
# Sourced by the entry script; inherits its strict mode, its notify() helper
|
||||
# and the STATE_DIR/LOG_FILE/APPS/REAL_BINARIES/PROCESS_MATCH globals it
|
||||
# defines.
|
||||
|
||||
# Ensure state directory exists
|
||||
ensure_state_dir() {
|
||||
mkdir -p "$STATE_DIR" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Log message with timestamp
|
||||
log_message() {
|
||||
local msg
|
||||
msg="$(printf '%(%Y-%m-%d %H:%M:%S)T' -1) - $1"
|
||||
echo "$msg" >&2
|
||||
echo "$msg" >>"$LOG_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Get current hour key (YYYY-MM-DD-HH format)
|
||||
get_hour_key() {
|
||||
printf '%(%Y-%m-%d-%H)T' -1
|
||||
}
|
||||
|
||||
# Get state file path for an app
|
||||
get_state_file() {
|
||||
local app="$1"
|
||||
echo "$STATE_DIR/${app}.lastopen"
|
||||
}
|
||||
|
||||
# Check if app was already opened this hour
|
||||
was_opened_this_hour() {
|
||||
local app="$1"
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
if [[ -f $state_file ]]; then
|
||||
local last_hour
|
||||
last_hour=$(cat "$state_file" 2>/dev/null || echo "")
|
||||
if [[ $last_hour == "$current_hour" ]]; then
|
||||
return 0 # Was opened this hour
|
||||
fi
|
||||
fi
|
||||
return 1 # Not opened this hour
|
||||
}
|
||||
|
||||
# Record app opening
|
||||
record_opening() {
|
||||
local app="$1"
|
||||
local state_file
|
||||
state_file=$(get_state_file "$app")
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
echo "$current_hour" >"$state_file"
|
||||
log_message "ALLOWED: $app opened (first time this hour: $current_hour)"
|
||||
}
|
||||
|
||||
# Block app and notify
|
||||
block_app() {
|
||||
local app="$1"
|
||||
local current_hour
|
||||
current_hour=$(get_hour_key)
|
||||
|
||||
log_message "BLOCKED: $app launch prevented (already opened this hour: $current_hour)"
|
||||
|
||||
# Send notification using common library
|
||||
notify "🚫 $app Blocked" "Already opened this hour. Wait until the next hour." critical 5000
|
||||
}
|
||||
|
||||
# Get real binary path for an app
|
||||
get_real_binary() {
|
||||
local app="$1"
|
||||
local wrapper_path="${APPS[$app]}"
|
||||
local real_binary="${REAL_BINARIES[$app]}"
|
||||
|
||||
# Check if wrapper is installed (original moved to .orig)
|
||||
if [[ -f "${wrapper_path}.orig" ]]; then
|
||||
# Wrapper installed, return the actual executable
|
||||
echo "$real_binary"
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Get running state file path for an app (tracks PID and start time)
|
||||
get_running_file() {
|
||||
local app="$1"
|
||||
echo "$STATE_DIR/${app}.running"
|
||||
}
|
||||
|
||||
# Clean up stale running state (process no longer running)
|
||||
# Uses process-name matching so Electron apps that fork don't appear stale.
|
||||
cleanup_stale_running_state() {
|
||||
local app="$1"
|
||||
local running_file
|
||||
running_file=$(get_running_file "$app")
|
||||
|
||||
if [[ ! -f $running_file ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Match on PROCESS_MATCH when the exec target is a launcher that exec()s away
|
||||
# (see the PROCESS_MATCH map); otherwise the exec target is the process.
|
||||
local real_binary="${PROCESS_MATCH[$app]:-${REAL_BINARIES[$app]}}"
|
||||
|
||||
# Check if any process matching the real binary is still running
|
||||
if ! is_app_running "$real_binary"; then
|
||||
log_message "CLEANUP: Stale running state for $app (no matching processes found)"
|
||||
rm -f "$running_file"
|
||||
fi
|
||||
}
|
||||
|
||||
# Check if app is running by process name (handles Electron apps that fork)
|
||||
is_app_running() {
|
||||
local real_binary="$1"
|
||||
pgrep -f "$real_binary" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Kill all processes matching the real binary path
|
||||
kill_app() {
|
||||
local real_binary="$1"
|
||||
pkill -f "$real_binary" 2>/dev/null || true
|
||||
sleep 2
|
||||
pkill -9 -f "$real_binary" 2>/dev/null || true
|
||||
}
|
||||
|
||||
# Check if auto-close is suspended for an app today
|
||||
is_autoclose_suspended() {
|
||||
local app="$1"
|
||||
local today
|
||||
today=$(printf '%(%Y-%m-%d)T' -1)
|
||||
local suspend_file="$STATE_DIR/${app}.suspend-autoclose"
|
||||
|
||||
if [[ -f $suspend_file ]]; then
|
||||
local suspend_date
|
||||
suspend_date=$(cat "$suspend_file" 2>/dev/null || echo "")
|
||||
if [[ $suspend_date == "$today" ]]; then
|
||||
return 0 # Suspended for today
|
||||
else
|
||||
# Stale suspend file, clean up
|
||||
rm -f "$suspend_file"
|
||||
fi
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
@ -0,0 +1,120 @@
|
||||
#!/bin/bash
|
||||
# App-launch path for block_compulsive_opening.sh: the auto-close timer and the
|
||||
# wrapper entry that the generated /usr/bin/<app> shims exec into.
|
||||
# Sourced by the entry script; inherits its strict mode and globals.
|
||||
|
||||
# Launch app with auto-close timer
|
||||
launch_with_timer() {
|
||||
local app="$1"
|
||||
local real_binary="$2"
|
||||
shift 2
|
||||
|
||||
# $real_binary is what we EXEC; $proc_match is what we look for in the process
|
||||
# table. They are usually identical, but NOT when the exec target is a launcher
|
||||
# that exec()s away: discord's /usr/bin/discord.orig replaces itself with
|
||||
# ~/.config/discord/<app>/Discord, so matching/killing on the launcher path
|
||||
# would find nothing — the auto-close daemon would think the app exited
|
||||
# instantly and the time limit would silently never fire.
|
||||
local proc_match="${PROCESS_MATCH[$app]:-$real_binary}"
|
||||
|
||||
# Check if auto-close is suspended for today
|
||||
if is_autoclose_suspended "$app"; then
|
||||
log_message "LAUNCHED: $app (auto-close suspended for today)"
|
||||
exec "$real_binary" "$@"
|
||||
fi
|
||||
|
||||
# Use per-app timeout if set, otherwise fall back to global default
|
||||
local timeout_minutes="${APP_TIMEOUT_MINUTES[$app]:-$AUTO_CLOSE_TIMEOUT_MINUTES}"
|
||||
local warning_seconds=$(((timeout_minutes - AUTO_CLOSE_WARNING_MINUTES) * 60))
|
||||
local running_file
|
||||
running_file=$(get_running_file "$app")
|
||||
|
||||
# Launch the app in background
|
||||
"$real_binary" "$@" &
|
||||
local app_pid=$!
|
||||
|
||||
# Give Electron apps time to fork before we start polling
|
||||
sleep 2
|
||||
|
||||
# Record state (FORK-FREE: use printf %s for timestamp)
|
||||
echo "$app_pid $(printf '%(%s)T' -1)" >"$running_file"
|
||||
log_message "LAUNCHED: $app with PID $app_pid (auto-close in ${timeout_minutes}m)"
|
||||
|
||||
# Spawn the auto-close daemon in a completely detached subshell
|
||||
# Uses process-name matching so it works for Electron apps that fork on launch
|
||||
(
|
||||
# Detach from terminal
|
||||
exec </dev/null >/dev/null 2>&1
|
||||
|
||||
# Wait for warning time
|
||||
sleep "$warning_seconds"
|
||||
|
||||
# Check if still running before warning (by process name, not PID)
|
||||
if is_app_running "$proc_match"; then
|
||||
# Send warning notification
|
||||
notify-send -u critical -t 30000 "⏰ $app Closing Soon" \
|
||||
"Session will end in ${AUTO_CLOSE_WARNING_MINUTES} minutes. Save your work!" 2>/dev/null || true
|
||||
else
|
||||
# Process already exited
|
||||
rm -f "$running_file" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Wait remaining time
|
||||
sleep $((AUTO_CLOSE_WARNING_MINUTES * 60))
|
||||
|
||||
# Check if still running (by process name)
|
||||
if is_app_running "$proc_match"; then
|
||||
# Send final notification
|
||||
notify-send -u critical -t 5000 "🚫 $app Session Ended" \
|
||||
"Time's up! Closing $app now." 2>/dev/null || true
|
||||
|
||||
# Kill all matching processes (handles forked Electron children)
|
||||
kill_app "$proc_match"
|
||||
|
||||
printf '%(%Y-%m-%d %H:%M:%S)T - AUTO-CLOSED: %s after %dm\n' -1 "$app" "${timeout_minutes}" >>"$LOG_FILE" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
rm -f "$running_file" 2>/dev/null || true
|
||||
) &
|
||||
disown
|
||||
|
||||
# Wait for the app to exit by polling process name.
|
||||
# Electron apps fork immediately so waiting on $app_pid would return too soon.
|
||||
while is_app_running "$proc_match"; do
|
||||
sleep 5
|
||||
done
|
||||
|
||||
# Clean up running state
|
||||
rm -f "$running_file" 2>/dev/null || true
|
||||
|
||||
log_message "EXITED: $app"
|
||||
}
|
||||
|
||||
# Main wrapper function - called when wrapping app launches
|
||||
wrapper_main() {
|
||||
local app="$1"
|
||||
shift
|
||||
|
||||
ensure_state_dir
|
||||
|
||||
local real_binary
|
||||
if ! real_binary=$(get_real_binary "$app"); then
|
||||
log_message "ERROR: Real binary not found for $app"
|
||||
echo "Error: Real binary for $app not found. Was the installer run?" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Clean up stale running state from previous crashes
|
||||
cleanup_stale_running_state "$app"
|
||||
|
||||
if was_opened_this_hour "$app"; then
|
||||
block_app "$app"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
record_opening "$app"
|
||||
|
||||
# Launch with auto-close timer (replaces direct exec)
|
||||
launch_with_timer "$app" "$real_binary" "$@"
|
||||
}
|
||||
@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env bash
|
||||
# Helpers sourced by the entry script.
|
||||
|
||||
cmd_setup() {
|
||||
set_actual_user_vars
|
||||
print_setup_header "Night Lockdown"
|
||||
|
||||
ensure_dir "$STATE_DIR"
|
||||
[[ -f "$STATE_FILE" ]] || echo UNLOCKED >"$STATE_FILE"
|
||||
|
||||
write_config
|
||||
install_enter_script
|
||||
install_unlock_script
|
||||
install_unlock_units
|
||||
install_rgb_off_service
|
||||
install_i2c_modules
|
||||
|
||||
systemctl daemon-reload
|
||||
enable_service night-lockdown-unlock.timer
|
||||
enable_service rgb-off.service
|
||||
|
||||
echo ""
|
||||
if verify_install; then
|
||||
log_ok "Night lockdown installed."
|
||||
else
|
||||
log_warn "Night lockdown installed with warnings (see above)."
|
||||
fi
|
||||
echo ""
|
||||
log_info "Next: swap the shutdown action by re-running setup_midnight_shutdown.sh"
|
||||
log_info " (it must call $ENTER_SCRIPT instead of powering off)."
|
||||
log_info "Emergency unlock over SSH: sudo $0 unlock"
|
||||
}
|
||||
|
||||
cmd_status() {
|
||||
local state="unknown"
|
||||
[[ -r "$STATE_FILE" ]] && state="$(cat "$STATE_FILE")"
|
||||
echo "Night lockdown state : $state"
|
||||
echo "lightdm.service : $(systemctl is-active lightdm.service 2>/dev/null || true)"
|
||||
echo "getty@.service mask : $(systemctl is-enabled getty@.service 2>/dev/null || true)"
|
||||
echo "autovt@.service mask : $(systemctl is-enabled autovt@.service 2>/dev/null || true)"
|
||||
echo "unlock timer : $(systemctl is-active night-lockdown-unlock.timer 2>/dev/null || true) / $(systemctl is-enabled night-lockdown-unlock.timer 2>/dev/null || true)"
|
||||
echo ""
|
||||
echo "Next unlock triggers:"
|
||||
systemctl list-timers night-lockdown-unlock.timer --no-pager 2>/dev/null || true
|
||||
}
|
||||
|
||||
cmd_unlock() {
|
||||
log_info "Emergency unlock: restoring GUI now"
|
||||
DRY_RUN="" "$UNLOCK_SCRIPT"
|
||||
echo ""
|
||||
log_warn "The curfew is still armed: the next 30-min check tick will re-lock."
|
||||
log_warn "To stay unlocked until morning, register an override (friction by design):"
|
||||
if [[ -x "$OVERRIDE_MANAGER" ]]; then
|
||||
local now_h until_str
|
||||
now_h="$(date '+%Y-%m-%d %H:%M')"
|
||||
# Next 05:00 boundary (tomorrow if already past 05:00 today).
|
||||
if [[ "$(date +%H)" -lt 5 ]]; then
|
||||
until_str="$(date '+%Y-%m-%d') 05:00"
|
||||
else
|
||||
until_str="$(date -d tomorrow '+%Y-%m-%d') 05:00"
|
||||
fi
|
||||
echo " sudo $OVERRIDE_MANAGER add '$now_h' '$until_str' 'emergency unlock'"
|
||||
else
|
||||
log_warn " (override manager not found at $OVERRIDE_MANAGER)"
|
||||
fi
|
||||
}
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Night Lockdown — replace the midnight power-off with a GUI lockout that keeps
|
||||
background servers running.
|
||||
|
||||
Usage:
|
||||
sudo $0 setup Install/refresh the lock+unlock action and morning timer
|
||||
$0 status Show current lockdown state and timer status
|
||||
sudo $0 unlock Emergency: lift the lockdown right now (use over SSH)
|
||||
$0 help Show this help
|
||||
|
||||
After 'setup', re-run setup_midnight_shutdown.sh so the scheduled check calls
|
||||
$ENTER_SCRIPT instead of powering off.
|
||||
EOF
|
||||
}
|
||||
@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
# Helpers sourced by the entry script.
|
||||
|
||||
# Detect ALSA card indices that expose a 'Master' control (space-separated).
|
||||
detect_alsa_cards() {
|
||||
local card cards=""
|
||||
for card in 0 1 2 3 4 5 6; do
|
||||
if amixer -c "$card" scontrols 2>/dev/null | grep -q "'Master'"; then
|
||||
cards+="${card} "
|
||||
fi
|
||||
done
|
||||
# Trim trailing space.
|
||||
echo "${cards% }"
|
||||
}
|
||||
|
||||
# Write /etc/night-lockdown.conf with values detected for THIS machine.
|
||||
write_config() {
|
||||
local user uid alsa_cards
|
||||
user="$ACTUAL_USER"
|
||||
uid="$(id -u "$user")"
|
||||
alsa_cards="$(detect_alsa_cards)"
|
||||
|
||||
log_info "Writing config to $CONF_FILE (user=$user uid=$uid alsa_cards='$alsa_cards')"
|
||||
cat >"$CONF_FILE" <<EOF
|
||||
$MANAGED_BANNER
|
||||
# Desktop user whose GUI session is torn down at lockdown.
|
||||
LOCK_USER="$user"
|
||||
LOCK_UID="$uid"
|
||||
|
||||
# ALSA card indices with a 'Master' control, muted at lockdown (best-effort).
|
||||
ALSA_CARDS="$alsa_cards"
|
||||
|
||||
# Kill all RGB via OpenRGB. Detected here: 2x ENE DRAM (RGB RAM, i2c 0x71/0x73),
|
||||
# ZOTAC RTX 3090 (GPU), ASRock B650M Pro RS (USB Polychrome 26ce:01a2).
|
||||
RGB_ENABLE="1"
|
||||
|
||||
# How to turn the lighting off. Use static + black, NOT the "off" mode:
|
||||
# - the ZOTAC GPU has no "Off" mode at all (its modes are Static/Breath/...);
|
||||
# - the ASRock board lists "Off" but silently ignores it (mode stayed Rainbow),
|
||||
# while static+black moves it to Static and goes dark.
|
||||
# All four devices support Static, so this one form works everywhere. Verified:
|
||||
# 'openrgb --mode static --color 000000' -> all 4 devices report ACTIVE: Static.
|
||||
RGB_OFF_MODE="static"
|
||||
RGB_OFF_COLOR="000000"
|
||||
|
||||
# HOME that openrgb runs with: it keeps its config under its own HOME, and
|
||||
# systemd (HOME=/root) vs sudo (HOME=/home/USER) would otherwise disagree about
|
||||
# where that config lives, so pin it for both directions.
|
||||
RGB_HOME="/root"
|
||||
|
||||
# User systemd units (graphical-session-bound) stopped at lockdown, space-sep.
|
||||
MONITORED_USER_UNITS="control-from-mobile.service"
|
||||
|
||||
# GUI tray processes (not systemd units) killed at lockdown, space-separated.
|
||||
MONITORED_PROCS="aw-qt"
|
||||
|
||||
# Text console to blank at lockdown. Stopping lightdm hands the VT back to fbcon,
|
||||
# which unblanks and prints kernel/systemd log spam instead of showing darkness.
|
||||
CONSOLE_TTY="/dev/tty1"
|
||||
|
||||
# How hard to blank the console (/sys/class/graphics/fbN/blank value):
|
||||
# 1 = FB_BLANK_NORMAL — screen black, monitor keeps its signal. SAFE.
|
||||
# 4 = FB_BLANK_POWERDOWN — DPMS off, monitor drops to standby.
|
||||
# Do NOT use 4 here: DisplayPort drops its link when powered down, and the GPU
|
||||
# then sees the connector as disconnected and will not re-train it on wake —
|
||||
# DP-0 vanished from xrandr and needed the cable physically re-plugged. HDMI
|
||||
# tolerates it, DP does not. 1 still gives a fully black screen, which is the
|
||||
# whole point, without touching the link.
|
||||
CONSOLE_BLANK_MODE="1"
|
||||
|
||||
# Never start the morning alarm earlier than lockdown-entry + this many hours,
|
||||
# even though the unlock timer itself still fires on its normal staggered
|
||||
# schedule (05:00/05:15/05:30/06:00/07:00). A late lockdown entry (e.g. 23:00
|
||||
# instead of the usual 21:00) must not still wake you 6h later.
|
||||
MIN_WAKE_AFTER_LOCKDOWN_HOURS="8"
|
||||
|
||||
# autorandr profile to restore after the GUI comes back up. Create it once with
|
||||
# 'autorandr --save default' while all monitors are connected and arranged the
|
||||
# way you want; the unlock script re-applies it so a DisplayPort link that
|
||||
# didn't re-enumerate cleanly doesn't require a manual xrandr/replug.
|
||||
AUTORANDR_PROFILE="default"
|
||||
|
||||
# Cap CPU/GPU power draw for the night as a safety net against anything left
|
||||
# running headless overnight (interactive GPU/CPU load dies with the GUI
|
||||
# teardown above, but a systemd service — e.g. ollama serving a request — does
|
||||
# not). Set to "0" to disable without touching the enter/unlock scripts.
|
||||
POWER_SAVE_ENABLE="1"
|
||||
|
||||
# AMD amd-pstate-epp hint applied to every core at lockdown (this machine is
|
||||
# Ryzen, not Intel, so intel_pstate/no_turbo does not apply). One of: default,
|
||||
# performance, balance_performance, balance_power, power, custom.
|
||||
CPU_EPP_NIGHT="power"
|
||||
|
||||
# nvidia-smi power limit (watts) applied at lockdown. Set to this card's
|
||||
# reported power.min_limit (100W on the RTX 3090 here) so a runaway overnight
|
||||
# CUDA job is bounded, not eliminated — persistence mode is deliberately left
|
||||
# alone so any legitimate headless GPU service keeps working, just slower.
|
||||
GPU_POWER_LIMIT_NIGHT_WATTS="100"
|
||||
|
||||
# Fully unbind the GPU from the PCI bus at lockdown (unload nvidia kernel
|
||||
# modules + PCI remove), rescanned back at unlock. Far more aggressive than
|
||||
# the power-limit cap above: recovers more idle wattage, but modprobe -r can
|
||||
# hang if anything still references the device, and a botched unbind might
|
||||
# need a hard power-cycle to recover -- which WOULD take every container down
|
||||
# with it (the one thing night-lockdown exists to prevent). Default OFF and
|
||||
# deliberately left off: the first real run of this is an uncorroborated test
|
||||
# on this exact kernel/driver, not a dress rehearsal -- nothing can safely
|
||||
# test it without also tearing down the GUI it runs under.
|
||||
GPU_UNBIND_ENABLE="0"
|
||||
EOF
|
||||
chmod 0644 "$CONF_FILE"
|
||||
|
||||
# This heredoc is intentionally UNQUOTED so the detected values above
|
||||
# interpolate — which also means a stray backtick or $ anywhere in it
|
||||
# (even inside a comment) gets executed/expanded and its output injected
|
||||
# into the file. That has bitten twice, and a corrupted config makes the
|
||||
# lock script fail to source it and silently skip steps. Fail loudly here
|
||||
# instead of shipping a broken config.
|
||||
if ! bash -n "$CONF_FILE" 2>/dev/null; then
|
||||
log_error "Generated $CONF_FILE is not valid shell — refusing to continue."
|
||||
log_error "Check write_config() for backticks or \$ in the heredoc."
|
||||
bash -n "$CONF_FILE" || true
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Helpers sourced by the entry script.
|
||||
|
||||
|
||||
# Where the verbatim payload files live. Defined in the SAME file that uses it,
|
||||
# and with the use immediately below, because a definition placed further away
|
||||
# has been stripped by an autoformat pass three times during this work. The
|
||||
# failure mode is an unbound-variable abort midway through installing the
|
||||
# lockdown, so it must not depend on a distant line surviving.
|
||||
: "${_NL_PAYLOAD_DIR:=$(cd "$(dirname "${BASH_SOURCE[0]}")/payloads" && pwd)}"
|
||||
install_enter_script() {
|
||||
log_info "Installing lock action to $ENTER_SCRIPT"
|
||||
# The payload is a DATA FILE, not a heredoc: inlining it put this lib over
|
||||
# the 250-line cap, and the body is a complete standalone script that is
|
||||
# easier to read, lint and diff on its own. The heredoc was quoted
|
||||
# (<<'ENTER_EOF'), so the body was already literal — copying it verbatim is
|
||||
# exactly equivalent. Verified by hashing the emitted result.
|
||||
install -m 0755 "$_NL_PAYLOAD_DIR/night-lockdown-enter.sh.in" "$ENTER_SCRIPT"
|
||||
}
|
||||
@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env bash
|
||||
# Helpers sourced by the entry script.
|
||||
|
||||
install_unlock_units() {
|
||||
log_info "Installing morning-unlock timer family"
|
||||
cat >"$UNLOCK_SERVICE" <<EOF
|
||||
$MANAGED_BANNER
|
||||
[Unit]
|
||||
Description=Lift night lockdown (restore GUI, unmute, unmask login surface)
|
||||
DefaultDependencies=false
|
||||
After=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=$UNLOCK_SCRIPT
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
EOF
|
||||
|
||||
# Multiple staggered triggers + Persistent=true = dead-man robustness: a
|
||||
# single missed/failed 05:00 run cannot strand the machine, and each run is
|
||||
# idempotent so repeated firing is harmless.
|
||||
cat >"$UNLOCK_TIMER" <<EOF
|
||||
$MANAGED_BANNER
|
||||
[Unit]
|
||||
Description=Morning triggers to lift night lockdown
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 05:00:00
|
||||
OnCalendar=*-*-* 05:15:00
|
||||
OnCalendar=*-*-* 05:30:00
|
||||
OnCalendar=*-*-* 06:00:00
|
||||
OnCalendar=*-*-* 07:00:00
|
||||
Persistent=true
|
||||
AccuracySec=1s
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
}
|
||||
|
||||
# Lights stay off at ALL times, not just during lockdown. The board firmware
|
||||
# re-lights RAM/board/GPU on every power-on, so without this the RGB would be
|
||||
# back after each reboot and only go dark again at the next 21:00 lock.
|
||||
install_rgb_off_service() {
|
||||
log_info "Installing boot-time RGB-off service"
|
||||
cat >"$RGB_OFF_SERVICE" <<EOF
|
||||
$MANAGED_BANNER
|
||||
[Unit]
|
||||
Description=Turn all RGB lighting off (lights are meant to be off at all times)
|
||||
After=multi-user.target
|
||||
# The i2c DRAM/GPU controllers need their buses; the ASRock controller is USB.
|
||||
Wants=systemd-modules-load.service
|
||||
After=systemd-modules-load.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
# HOME pinned for the same reason as in the lock/unlock scripts: openrgb keeps
|
||||
# its state under HOME and systemd would otherwise differ from an interactive
|
||||
# sudo run. Detection takes ~2s before it applies. static+black rather than
|
||||
# "off": the ZOTAC GPU has no Off mode and the ASRock board ignores it.
|
||||
ExecStart=/usr/bin/env HOME=${RGB_HOME_DEFAULT} /usr/bin/openrgb --mode static --color 000000
|
||||
SuccessExitStatus=0 1
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
}
|
||||
|
||||
verify_install() {
|
||||
log_info "Verifying installation"
|
||||
local ok=true
|
||||
local path
|
||||
for path in "$ENTER_SCRIPT" "$UNLOCK_SCRIPT" "$CONF_FILE" \
|
||||
"$UNLOCK_SERVICE" "$UNLOCK_TIMER" "$RGB_OFF_SERVICE" "$I2C_MODULES_FILE"; do
|
||||
if [[ -e "$path" ]]; then
|
||||
log_ok "present: $path"
|
||||
else
|
||||
log_error "missing: $path"
|
||||
ok=false
|
||||
fi
|
||||
done
|
||||
if is_service_enabled night-lockdown-unlock.timer; then
|
||||
log_ok "night-lockdown-unlock.timer is enabled"
|
||||
else
|
||||
log_error "night-lockdown-unlock.timer is NOT enabled"
|
||||
ok=false
|
||||
fi
|
||||
# The action swap in the fortress check script is what actually invokes us.
|
||||
if grep -q "$ENTER_SCRIPT" /usr/local/bin/day-specific-shutdown-check.sh 2>/dev/null; then
|
||||
log_ok "day-specific-shutdown-check.sh calls the lockdown action"
|
||||
else
|
||||
log_warn "day-specific-shutdown-check.sh does NOT call $ENTER_SCRIPT yet"
|
||||
log_warn " → re-run setup_midnight_shutdown.sh to regenerate it (see header)"
|
||||
fi
|
||||
[[ "$ok" == true ]]
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Helpers sourced by the entry script.
|
||||
|
||||
|
||||
# Where the verbatim payload files live. Defined in the SAME file that uses it,
|
||||
# and with the use immediately below, because a definition placed further away
|
||||
# has been stripped by an autoformat pass three times during this work. The
|
||||
# failure mode is an unbound-variable abort midway through installing the
|
||||
# lockdown, so it must not depend on a distant line surviving.
|
||||
: "${_NL_PAYLOAD_DIR:=$(cd "$(dirname "${BASH_SOURCE[0]}")/payloads" && pwd)}"
|
||||
install_unlock_script() {
|
||||
log_info "Installing reversal to $UNLOCK_SCRIPT"
|
||||
# The payload is a DATA FILE, not a heredoc: inlining it put this lib over
|
||||
# the 250-line cap, and the body is a complete standalone script that is
|
||||
# easier to read, lint and diff on its own. The heredoc was quoted
|
||||
# (<<'UNLOCK_EOF'), so the body was already literal — copying it verbatim is
|
||||
# exactly equivalent. Verified by hashing the emitted result.
|
||||
install -m 0755 "$_NL_PAYLOAD_DIR/night-lockdown-unlock.sh.in" "$UNLOCK_SCRIPT"
|
||||
}
|
||||
@ -0,0 +1,279 @@
|
||||
#!/bin/bash
|
||||
# Managed by setup_night_lockdown.sh — do not edit by hand.
|
||||
#
|
||||
# Enter night lockdown: tear down the user GUI and mask the TTY login surface so
|
||||
# the machine is unusable from the keyboard, while every background server keeps
|
||||
# running. Reversed by night-lockdown-unlock.sh (05:00 timer or SSH recovery).
|
||||
# All steps are best-effort and logged; DRY_RUN=1 logs intended actions only.
|
||||
set -euo pipefail
|
||||
|
||||
readonly CONF_FILE="/etc/night-lockdown.conf"
|
||||
readonly STATE_DIR="/var/lib/night-lockdown"
|
||||
readonly STATE_FILE="$STATE_DIR/state"
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
[[ -r "$CONF_FILE" ]] && source "$CONF_FILE"
|
||||
LOCK_USER="${LOCK_USER:-}"
|
||||
LOCK_UID="${LOCK_UID:-}"
|
||||
ALSA_CARDS="${ALSA_CARDS:-}"
|
||||
RGB_ENABLE="${RGB_ENABLE:-1}"
|
||||
MONITORED_USER_UNITS="${MONITORED_USER_UNITS:-}"
|
||||
MONITORED_PROCS="${MONITORED_PROCS:-}"
|
||||
MIN_WAKE_AFTER_LOCKDOWN_HOURS="${MIN_WAKE_AFTER_LOCKDOWN_HOURS:-8}"
|
||||
CONSOLE_TTY="${CONSOLE_TTY:-/dev/tty1}"
|
||||
CONSOLE_BLANK_MODE="${CONSOLE_BLANK_MODE:-1}"
|
||||
POWER_SAVE_ENABLE="${POWER_SAVE_ENABLE:-1}"
|
||||
CPU_EPP_NIGHT="${CPU_EPP_NIGHT:-power}"
|
||||
GPU_POWER_LIMIT_NIGHT_WATTS="${GPU_POWER_LIMIT_NIGHT_WATTS:-100}"
|
||||
GPU_UNBIND_ENABLE="${GPU_UNBIND_ENABLE:-0}"
|
||||
DRY_RUN="${DRY_RUN:-}"
|
||||
|
||||
logg() { logger -t night-lockdown "$*"; printf 'night-lockdown: %s\n' "$*"; }
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN NOTE: log-only — lightdm is never actually stopped and the"
|
||||
logg "DRY_RUN NOTE: console framebuffer is never actually touched. This CANNOT"
|
||||
logg "DRY_RUN NOTE: exercise the blank-vs-VT-switch timing race (bug: visible"
|
||||
logg "DRY_RUN NOTE: console text). A clean DRY_RUN run is NOT proof that fix"
|
||||
logg "DRY_RUN NOTE: works — only a real run (DRY_RUN unset) validates it."
|
||||
logg "DRY_RUN NOTE: The CPU EPP write, nvidia-smi power-limit cap, and (if"
|
||||
logg "DRY_RUN NOTE: enabled) GPU PCI-unbind are also never actually applied"
|
||||
logg "DRY_RUN NOTE: under DRY_RUN — real-hardware timing/driver behavior for"
|
||||
logg "DRY_RUN NOTE: those is unverified until a real run."
|
||||
fi
|
||||
|
||||
# Run a command best-effort: log-only under DRY_RUN, never abort the lockdown.
|
||||
run() {
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: $*"
|
||||
return 0
|
||||
fi
|
||||
if ! "$@"; then
|
||||
logg "WARN: command failed (continuing): $*"
|
||||
fi
|
||||
}
|
||||
|
||||
# Run a command as the desktop user inside their session bus.
|
||||
run_as_user() {
|
||||
[[ -n "$LOCK_USER" && -n "$LOCK_UID" && -d "/run/user/$LOCK_UID" ]] || return 0
|
||||
run sudo -u "$LOCK_USER" env "XDG_RUNTIME_DIR=/run/user/$LOCK_UID" "$@"
|
||||
}
|
||||
|
||||
# Silence everything that prints to the text console. Once lightdm stops, the VT
|
||||
# reverts to fbcon and any kernel/systemd message lights the screen back up.
|
||||
silence_console() {
|
||||
# systemd status messages ("Starting/Stopped ...") -> off. RTMIN+20 re-enables.
|
||||
run kill -s RTMIN+21 1
|
||||
# Kernel messages -> console. Save the current printk so unlock can restore it.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
cat /proc/sys/kernel/printk >"$STATE_DIR/printk.prev" 2>/dev/null || true
|
||||
fi
|
||||
run sysctl -q -w "kernel.printk=1 4 1 4"
|
||||
}
|
||||
|
||||
# Force the console dark — black screen, but WITHOUT DPMS power management.
|
||||
# Powering the output down (FB_BLANK_POWERDOWN / setterm --powersave powerdown)
|
||||
# makes DisplayPort drop its link; the GPU then reports the connector
|
||||
# disconnected and never re-trains it, so the monitor is gone from xrandr until
|
||||
# the cable is physically re-plugged. Blanking alone is enough to go black.
|
||||
blank_console() {
|
||||
local fb
|
||||
for fb in /sys/class/graphics/fb*/blank; do
|
||||
[[ -e "$fb" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write $CONSOLE_BLANK_MODE (blank) > $fb"
|
||||
continue
|
||||
fi
|
||||
echo "$CONSOLE_BLANK_MODE" >"$fb" 2>/dev/null || logg "WARN: could not blank $fb"
|
||||
done
|
||||
# setterm emits escape sequences on stdout; from a systemd service stdout is
|
||||
# the journal, so aim it at the VT explicitly. --powersave off keeps DPMS out
|
||||
# of it so the DP link survives.
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would force console blank (no DPMS) on $CONSOLE_TTY"
|
||||
elif [[ -w "$CONSOLE_TTY" ]]; then
|
||||
setterm --term linux --blank force --powersave off \
|
||||
>"$CONSOLE_TTY" 2>/dev/null || logg "WARN: setterm blank failed"
|
||||
fi
|
||||
}
|
||||
|
||||
mkdir -p "$STATE_DIR"
|
||||
|
||||
# 1. Idempotency — entering lockdown when already locked is a safe no-op.
|
||||
if [[ "$(cat "$STATE_FILE" 2>/dev/null || echo UNLOCKED)" == "LOCKED" ]]; then
|
||||
logg "already LOCKED — nothing to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
logg "entering night lockdown"
|
||||
|
||||
# 2. RGB off (RAM + board + GPU), remembering the current lighting first.
|
||||
#
|
||||
# Do NOT gate this on `openrgb --list-devices`: that call is broken in the
|
||||
# installed openrgb-git build — it returns in ~70ms, before async detection
|
||||
# finishes, so it always reports zero devices. (That false "no controllers"
|
||||
# reading is why this step silently no-op'd.) The fix was to install stable
|
||||
# openrgb 1.0rc3 from extra, whose CLI detects properly (~1.9s) before acting.
|
||||
if [[ "$RGB_ENABLE" == "1" ]] && command -v openrgb >/dev/null 2>&1; then
|
||||
run env HOME="$RGB_HOME" openrgb --mode "$RGB_OFF_MODE" --color "$RGB_OFF_COLOR"
|
||||
fi
|
||||
|
||||
# 2b. Cap CPU/GPU power draw for the night. Save the pre-lockdown values first
|
||||
# so unlock restores exactly what was there, not a hardcoded "default" —
|
||||
# the user may have changed either away from factory settings.
|
||||
# Capture is guarded on the .prev file NOT already existing: this step
|
||||
# runs before state is written LOCKED (step 5), so a kill between here and
|
||||
# there leaves state UNLOCKED and the 30-min curfew check re-invokes this
|
||||
# whole script. Without the guard, that re-run would recapture "prev" from
|
||||
# the already-applied NIGHT value, permanently stranding the machine in
|
||||
# night power-save mode. unlock deletes the .prev file after a successful
|
||||
# restore, so a normal (non-crashed) cycle still captures fresh each night.
|
||||
if [[ "$POWER_SAVE_ENABLE" == "1" ]]; then
|
||||
if [[ -f /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference ]]; then
|
||||
if [[ "$DRY_RUN" != "1" && ! -f "$STATE_DIR/cpu_epp.prev" ]]; then
|
||||
cat /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference \
|
||||
>"$STATE_DIR/cpu_epp.prev" 2>/dev/null || true
|
||||
fi
|
||||
for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
|
||||
[[ -e "$epp_file" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write $CPU_EPP_NIGHT > $epp_file"
|
||||
else
|
||||
echo "$CPU_EPP_NIGHT" >"$epp_file" 2>/dev/null || logg "WARN: could not set EPP on $epp_file"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if command -v nvidia-smi >/dev/null 2>&1; then
|
||||
if [[ "$DRY_RUN" != "1" && ! -f "$STATE_DIR/gpu_power_limit_watts.prev" ]]; then
|
||||
nvidia-smi --query-gpu=power.limit --format=csv,noheader,nounits \
|
||||
>"$STATE_DIR/gpu_power_limit_watts.prev" 2>/dev/null || true
|
||||
fi
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: timeout 10 nvidia-smi -pl $GPU_POWER_LIMIT_NIGHT_WATTS"
|
||||
else
|
||||
run timeout 10 nvidia-smi -pl "$GPU_POWER_LIMIT_NIGHT_WATTS"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Mute audio (best-effort). The session teardown below silences apps anyway;
|
||||
# this covers any direct-ALSA sound. PipeWire is intentionally NOT touched, so
|
||||
# the morning unlock cannot be defeated by a persisted wireplumber mute.
|
||||
for card in $ALSA_CARDS; do
|
||||
command -v amixer >/dev/null 2>&1 && run amixer -c "$card" -q set Master mute
|
||||
done
|
||||
|
||||
# 4. Stop GUI-bound user units + tray apps (they die with X anyway; be tidy).
|
||||
for unit in $MONITORED_USER_UNITS; do
|
||||
run_as_user systemctl --user stop "$unit"
|
||||
done
|
||||
for proc in $MONITORED_PROCS; do
|
||||
# Only kill if actually running — pkill exits 1 on no-match, which would log
|
||||
# a misleading "command failed" WARN every night for an app that isn't up.
|
||||
if [[ -n "$LOCK_USER" ]] && pgrep -u "$LOCK_USER" -x "$proc" >/dev/null 2>&1; then
|
||||
run pkill -u "$LOCK_USER" -x "$proc"
|
||||
fi
|
||||
done
|
||||
|
||||
# 5. Persist the LOCKED intent BEFORE the session-killing teardown. Stopping
|
||||
# lightdm tears down the graphical session that this very process runs in, so
|
||||
# if we wrote state AFTER the teardown, a kill mid-teardown would leave state
|
||||
# at UNLOCKED — and the unlock path (which no-ops when UNLOCKED) would then
|
||||
# fail to restore, stranding the machine. Write intent first; any unlock
|
||||
# (05:00 timer, dead-man, or manual) then correctly restores.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
echo LOCKED >"$STATE_FILE"
|
||||
lockdown_epoch="$(date +%s)"
|
||||
echo "$lockdown_epoch" >"$STATE_DIR/locked_at_epoch"
|
||||
|
||||
# 5a. Schedule a one-shot wake-floor trigger for exactly
|
||||
# lockdown_epoch + MIN_WAKE_AFTER_LOCKDOWN_HOURS. The staggered
|
||||
# 05:00/05:15/05:30/06:00/07:00 unlock triggers are a fixed list sized
|
||||
# for the usual shutdown hours (~21:00-23:00), but the shutdown hour
|
||||
# itself is configurable (/etc/shutdown-schedule.conf) and changes
|
||||
# dynamically (see the sick-day feature). If lockdown ever starts late
|
||||
# enough that the floor lands after every remaining fixed trigger, the
|
||||
# alarm would otherwise silently never fire that morning. This
|
||||
# transient timer fires at the exact floor moment for THIS lockdown
|
||||
# regardless of what time it actually started, re-running the
|
||||
# (idempotent, self-dedup'd) unlock script, which is where the alarm
|
||||
# is actually attempted.
|
||||
floor_epoch=$((lockdown_epoch + MIN_WAKE_AFTER_LOCKDOWN_HOURS * 3600))
|
||||
floor_cal="$(date -d "@$floor_epoch" '+%Y-%m-%d %H:%M:%S')"
|
||||
run systemd-run --unit=night-lockdown-wake-floor --collect \
|
||||
--on-calendar="$floor_cal" /usr/local/bin/night-lockdown-unlock.sh
|
||||
else
|
||||
logg "DRY_RUN: would schedule a one-shot wake-floor trigger ~${MIN_WAKE_AFTER_LOCKDOWN_HOURS}h from now"
|
||||
fi
|
||||
|
||||
# 6a. Silence the console BEFORE stopping the GUI, so the teardown itself
|
||||
# ("Stopping Light Display Manager...") does not print onto the VT.
|
||||
silence_console
|
||||
|
||||
# 6. Mask the login surface BEFORE stopping the GUI, so logind cannot spawn a
|
||||
# getty into the gap. Mask ONLY getty@.service: autovt@.service is an alias
|
||||
# symlink to it, so masking getty@ already makes autovt@ttyN resolve to
|
||||
# masked ("Unit autovt@ttyN.service is masked" — logind cannot spawn a VT
|
||||
# login). Passing autovt@ to mask instead FAILS ("File
|
||||
# /etc/systemd/system/autovt@.service already exists and is a symlink"),
|
||||
# which is what produced the nightly WARN. Masks are /dev/null symlinks that
|
||||
# persist across reboot; the unlock path unmasks them.
|
||||
run systemctl mask getty@.service
|
||||
run systemctl stop 'getty@*.service'
|
||||
|
||||
# 7. Stop the GUI while continuously re-blanking the console in the
|
||||
# background. Activating a VT (which happens somewhere mid-way through the
|
||||
# GUI stop, not only once "systemctl stop" fully returns) makes fbcon
|
||||
# redraw/unblank as part of the switch, so a single blank-after-the-fact
|
||||
# call leaves a gap showing whatever was last on the console (old
|
||||
# kernel/systemd text) for however long the rest of the stop sequence
|
||||
# takes. Keep forcing it dark for the whole teardown instead of waiting.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
(
|
||||
while :; do
|
||||
blank_console
|
||||
sleep 0.1
|
||||
done
|
||||
) &
|
||||
BLANK_POLLER_PID=$!
|
||||
fi
|
||||
run systemctl stop lightdm.service
|
||||
if [[ -n "${BLANK_POLLER_PID:-}" ]]; then
|
||||
kill "$BLANK_POLLER_PID" 2>/dev/null || true
|
||||
wait "$BLANK_POLLER_PID" 2>/dev/null || true
|
||||
unset BLANK_POLLER_PID
|
||||
fi
|
||||
|
||||
# 8. Final guaranteed blank now that the GUI is fully down.
|
||||
blank_console
|
||||
|
||||
# 9. Optionally unbind the GPU entirely (default OFF — see GPU_UNBIND_ENABLE
|
||||
# comment in night-lockdown.conf for the risk tradeoff). Only ever runs
|
||||
# after the GUI is torn down, since nothing interactive needs the GPU at
|
||||
# this point. Timeout-guarded: modprobe -r can hang if anything still
|
||||
# references the device, and a hang here must not block the rest of
|
||||
# lockdown.
|
||||
if [[ "$GPU_UNBIND_ENABLE" == "1" ]] && command -v nvidia-smi >/dev/null 2>&1; then
|
||||
gpu_pci="$(lspci -d 10de: 2>/dev/null | grep -i 'VGA\|3D' | awk '{print $1}' | head -1)"
|
||||
if [[ -z "$gpu_pci" ]]; then
|
||||
logg "WARN: GPU_UNBIND_ENABLE=1 but no nvidia PCI device found"
|
||||
elif [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would unload nvidia modules and remove PCI device 0000:$gpu_pci"
|
||||
elif timeout 20 modprobe -r nvidia_uvm nvidia_drm nvidia_modeset nvidia 2>&1 | logger -t night-lockdown; then
|
||||
if echo 1 >"/sys/bus/pci/devices/0000:$gpu_pci/remove" 2>/dev/null; then
|
||||
logg "GPU unbound (0000:$gpu_pci removed from PCI bus)"
|
||||
# Unloading nvidia_drm / the PCI remove can surface a fallback
|
||||
# framebuffer that isn't blanked -- same failure class the
|
||||
# continuous re-blank during the lightdm stop (above) exists to
|
||||
# close, just triggered by module unload instead of a VT switch.
|
||||
blank_console
|
||||
else
|
||||
logg "WARN: modules unloaded but PCI remove failed for 0000:$gpu_pci"
|
||||
fi
|
||||
else
|
||||
logg "WARN: modprobe -r timed out or failed -- GPU left bound, skipping unbind"
|
||||
fi
|
||||
fi
|
||||
|
||||
logg "night lockdown active — servers up, GUI down, login surface masked, console dark"
|
||||
@ -0,0 +1,212 @@
|
||||
#!/bin/bash
|
||||
# Managed by setup_night_lockdown.sh — do not edit by hand.
|
||||
#
|
||||
# Lift night lockdown: unmask the login surface, restart the GUI, unmute audio.
|
||||
# Idempotent (safe to fire from the 5 staggered morning triggers and manual runs)
|
||||
# and deliberately independent of the shutdown fortress, so it can always run.
|
||||
set -euo pipefail
|
||||
|
||||
readonly CONF_FILE="/etc/night-lockdown.conf"
|
||||
readonly STATE_DIR="/var/lib/night-lockdown"
|
||||
readonly STATE_FILE="$STATE_DIR/state"
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
[[ -r "$CONF_FILE" ]] && source "$CONF_FILE"
|
||||
ALSA_CARDS="${ALSA_CARDS:-}"
|
||||
LOCK_USER="${LOCK_USER:-}"
|
||||
LOCK_UID="${LOCK_UID:-}"
|
||||
MIN_WAKE_AFTER_LOCKDOWN_HOURS="${MIN_WAKE_AFTER_LOCKDOWN_HOURS:-8}"
|
||||
AUTORANDR_PROFILE="${AUTORANDR_PROFILE:-default}"
|
||||
CONSOLE_TTY="${CONSOLE_TTY:-/dev/tty1}"
|
||||
RGB_ENABLE="${RGB_ENABLE:-1}"
|
||||
RGB_OFF_MODE="${RGB_OFF_MODE:-static}"
|
||||
RGB_OFF_COLOR="${RGB_OFF_COLOR:-000000}"
|
||||
RGB_HOME="${RGB_HOME:-/root}"
|
||||
POWER_SAVE_ENABLE="${POWER_SAVE_ENABLE:-1}"
|
||||
GPU_UNBIND_ENABLE="${GPU_UNBIND_ENABLE:-0}"
|
||||
DRY_RUN="${DRY_RUN:-}"
|
||||
|
||||
logg() { logger -t night-lockdown "$*"; printf 'night-lockdown: %s\n' "$*"; }
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN NOTE: log-only — lightdm is never actually started and"
|
||||
logg "DRY_RUN NOTE: autorandr is never actually invoked. This CANNOT exercise"
|
||||
logg "DRY_RUN NOTE: the real DisplayPort reconnect or graphical-session wait."
|
||||
logg "DRY_RUN NOTE: A clean DRY_RUN run is NOT proof those work — only a real"
|
||||
logg "DRY_RUN NOTE: run (DRY_RUN unset) validates them. The alarm floor/dedup"
|
||||
logg "DRY_RUN NOTE: logic (locked_at_epoch) IS exercised"
|
||||
logg "DRY_RUN NOTE: faithfully here, since that part is pure calculation."
|
||||
logg "DRY_RUN NOTE: The CPU EPP / GPU power-limit restore and (if enabled)"
|
||||
logg "DRY_RUN NOTE: the PCI rescan are also never actually applied under"
|
||||
logg "DRY_RUN NOTE: DRY_RUN — real-hardware timing/driver behavior for"
|
||||
logg "DRY_RUN NOTE: those is unverified until a real run."
|
||||
fi
|
||||
|
||||
run() {
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: $*"
|
||||
return 0
|
||||
fi
|
||||
if ! "$@"; then
|
||||
logg "WARN: command failed (continuing): $*"
|
||||
fi
|
||||
}
|
||||
|
||||
# NOTE: this script used to also start morning-routine.service here, on a
|
||||
# fixed 05:00/05:15/05:30/06:00/07:00 ladder. wake-alarm-trigger.timer now
|
||||
# owns firing the alarm: it ticks every minute and fires at the time the
|
||||
# phone synced, so the alarm follows the phone instead of a hardcoded hour.
|
||||
# Keeping both meant a 07:00 alarm on a morning the phone said 08:00.
|
||||
|
||||
mkdir -p "$STATE_DIR"
|
||||
|
||||
# Idempotency — lifting when already unlocked is a safe no-op.
|
||||
if [[ "$(cat "$STATE_FILE" 2>/dev/null || echo UNLOCKED)" == "UNLOCKED" ]]; then
|
||||
logg "already UNLOCKED — nothing else to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
logg "lifting night lockdown"
|
||||
|
||||
# 0. Restore the console: unblank it and let kernel/systemd talk to it again.
|
||||
# Must happen even if everything below fails, or the machine would stay
|
||||
# permanently silent on the console after any unlock.
|
||||
restore_console() {
|
||||
local fb prev
|
||||
for fb in /sys/class/graphics/fb*/blank; do
|
||||
[[ -e "$fb" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write 0 (unblank) > $fb"
|
||||
continue
|
||||
fi
|
||||
echo 0 >"$fb" 2>/dev/null || true
|
||||
done
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would restore printk + systemd status messages"
|
||||
return 0
|
||||
fi
|
||||
[[ -w "$CONSOLE_TTY" ]] && setterm --term linux --blank poke --powersave off \
|
||||
>"$CONSOLE_TTY" 2>/dev/null
|
||||
if [[ -r "$STATE_DIR/printk.prev" ]]; then
|
||||
prev="$(cat "$STATE_DIR/printk.prev")"
|
||||
[[ -n "$prev" ]] && sysctl -q -w "kernel.printk=$prev" 2>/dev/null
|
||||
fi
|
||||
kill -s RTMIN+20 1 2>/dev/null || true # systemd: status messages back on
|
||||
}
|
||||
restore_console
|
||||
|
||||
# 1. Unmask the login surface (undo the persistent /dev/null mask). Only
|
||||
# getty@.service is ever masked; autovt@.service is just an alias to it.
|
||||
run systemctl unmask getty@.service
|
||||
|
||||
# 1a. If the GPU was unbound at lockdown, rescan the PCI bus to bring it back
|
||||
# before starting the GUI. Harmless no-op if nothing was removed. Polls
|
||||
# for the driver actually being ready (nvidia-smi succeeding) rather than
|
||||
# a fixed sleep -- starting lightdm against a GPU that hasn't finished
|
||||
# reprobing risks a failed X start, which (unlike a mis-enumerated
|
||||
# display) the autorandr retry loop above cannot recover from.
|
||||
if [[ "$GPU_UNBIND_ENABLE" == "1" ]]; then
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would rescan PCI bus and wait for the GPU driver to be ready"
|
||||
else
|
||||
echo 1 >/sys/bus/pci/rescan 2>/dev/null || logg "WARN: PCI rescan failed"
|
||||
gpu_ready=false
|
||||
for ((i = 0; i < 15; i++)); do
|
||||
if nvidia-smi >/dev/null 2>&1; then
|
||||
gpu_ready=true
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [[ "$gpu_ready" == true ]]; then
|
||||
logg "GPU driver ready after PCI rescan"
|
||||
else
|
||||
logg "WARN: GPU driver not ready after rescan + 15s -- starting GUI anyway"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Start the GUI — lightdm autologins back into i3/dwm.
|
||||
run systemctl start lightdm.service
|
||||
|
||||
# 2a. Reconnect/reconfigure displays. A DisplayPort link does not always
|
||||
# re-enumerate cleanly on its own after the console teardown, leaving a
|
||||
# monitor disconnected until someone runs xrandr by hand. Retry autorandr
|
||||
# for a bit while the session comes up instead. Requires a saved profile
|
||||
# ('autorandr --save default' run once while all monitors are connected).
|
||||
if [[ -n "$LOCK_USER" && -n "$LOCK_UID" ]] && command -v autorandr >/dev/null 2>&1; then
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run autorandr --change as $LOCK_USER"
|
||||
else
|
||||
autorandr_ok=false
|
||||
for ((i = 0; i < 15; i++)); do
|
||||
if sudo -u "$LOCK_USER" env "XDG_RUNTIME_DIR=/run/user/$LOCK_UID" DISPLAY=:0 \
|
||||
autorandr --change --default "$AUTORANDR_PROFILE" >/dev/null 2>&1; then
|
||||
autorandr_ok=true
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [[ "$autorandr_ok" == true ]]; then
|
||||
logg "autorandr: displays restored (profile '$AUTORANDR_PROFILE')"
|
||||
else
|
||||
logg "WARN: autorandr did not settle after retries — displays may need manual xrandr"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Restore audio (unmute the cards muted at lockdown).
|
||||
for card in $ALSA_CARDS; do
|
||||
command -v amixer >/dev/null 2>&1 && run amixer -c "$card" -q set Master unmute
|
||||
done
|
||||
|
||||
# 3b. Restore CPU EPP and GPU power limit to their pre-lockdown values (saved
|
||||
# by night-lockdown-enter.sh). Missing state file = enter never ran the
|
||||
# power-save step (e.g. it was disabled then) — nothing to restore.
|
||||
# Delete each .prev file after a successful (non-DRY_RUN) restore: enter's
|
||||
# capture is guarded on the file NOT existing (crash-safety, see its own
|
||||
# comment), so leaving a stale file here would freeze future captures to
|
||||
# tonight's value forever instead of tracking whatever the user's daytime
|
||||
# setting actually is.
|
||||
if [[ "$POWER_SAVE_ENABLE" == "1" ]]; then
|
||||
if [[ -r "$STATE_DIR/cpu_epp.prev" ]]; then
|
||||
prev_epp="$(cat "$STATE_DIR/cpu_epp.prev")"
|
||||
if [[ -n "$prev_epp" ]]; then
|
||||
for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
|
||||
[[ -e "$epp_file" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write $prev_epp > $epp_file"
|
||||
else
|
||||
echo "$prev_epp" >"$epp_file" 2>/dev/null || logg "WARN: could not restore EPP on $epp_file"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
[[ "$DRY_RUN" == "1" ]] || rm -f "$STATE_DIR/cpu_epp.prev"
|
||||
fi
|
||||
|
||||
if command -v nvidia-smi >/dev/null 2>&1 && [[ -r "$STATE_DIR/gpu_power_limit_watts.prev" ]]; then
|
||||
prev_watts="$(cat "$STATE_DIR/gpu_power_limit_watts.prev")"
|
||||
if [[ -n "$prev_watts" ]]; then
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: timeout 10 nvidia-smi -pl $prev_watts"
|
||||
else
|
||||
run timeout 10 nvidia-smi -pl "$prev_watts"
|
||||
fi
|
||||
fi
|
||||
[[ "$DRY_RUN" == "1" ]] || rm -f "$STATE_DIR/gpu_power_limit_watts.prev"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 4. Re-assert lights-off rather than restoring anything: the preference is no
|
||||
# lighting at all, ever, so the morning must not turn the RGB back on.
|
||||
if [[ "$RGB_ENABLE" == "1" ]] && command -v openrgb >/dev/null 2>&1; then
|
||||
run env HOME="$RGB_HOME" openrgb --mode "$RGB_OFF_MODE" --color "$RGB_OFF_COLOR"
|
||||
fi
|
||||
|
||||
# 5. Record state BEFORE the (possibly long) alarm wait, so re-fired unlock
|
||||
# triggers dedupe on the state token instead of double-starting things.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
echo UNLOCKED >"$STATE_FILE"
|
||||
fi
|
||||
|
||||
logg "night lockdown lifted — GUI restored, login surface unmasked"
|
||||
@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env bash
|
||||
# lib/tests/cco_harness.sh — shared fixture for the block_compulsive_opening.sh split.
|
||||
#
|
||||
# Sourced, not executed. Scope: the hour-key/state logic that decides whether an
|
||||
# app launch is allowed. Everything that moves system binaries (install_wrapper,
|
||||
# uninstall_wrapper, install_all) or kills processes (kill_app, launch_with_timer)
|
||||
# is NOT executed here — this machine's beeper/signal/discord wrappers and a live
|
||||
# pacman hook depend on those paths, and a test that ran them would rewrite them.
|
||||
#
|
||||
# STATE_DIR and LOG_FILE were already variables in the pre-split script, so the
|
||||
# tests point them at a tmpdir and nothing touches ~/.local/state.
|
||||
set -euo pipefail
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
_t_pass() {
|
||||
PASS=$((PASS + 1))
|
||||
printf ' OK: %s\n' "$1"
|
||||
}
|
||||
|
||||
_t_fail() {
|
||||
FAIL=$((FAIL + 1))
|
||||
printf ' FAIL: %s\n' "$1"
|
||||
}
|
||||
|
||||
_t_eq() {
|
||||
local want="$1"
|
||||
local got="$2"
|
||||
local what="$3"
|
||||
if [[ $got == "$want" ]]; then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (want '${want}', got '${got}')"
|
||||
fi
|
||||
}
|
||||
|
||||
_t_has() {
|
||||
local haystack="$1"
|
||||
local needle="$2"
|
||||
local what="$3"
|
||||
if [[ $haystack == *"$needle"* ]]; then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (want a substring '${needle}')"
|
||||
fi
|
||||
}
|
||||
|
||||
# These helpers return 0/1 to mean allowed/blocked, and which way they fail is
|
||||
# the whole point — assert on the status explicitly rather than letting `set -e`
|
||||
# end the run. Called via `if` so a non-zero return does not abort the suite.
|
||||
_t_true() {
|
||||
local what="$2"
|
||||
if ("$1"); then
|
||||
_t_pass "$what"
|
||||
else
|
||||
_t_fail "$what (expected success, got non-zero)"
|
||||
fi
|
||||
}
|
||||
|
||||
_t_false() {
|
||||
local what="$2"
|
||||
if ("$1"); then
|
||||
_t_fail "$what (expected non-zero, got success)"
|
||||
else
|
||||
_t_pass "$what"
|
||||
fi
|
||||
}
|
||||
|
||||
CCO_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
export CCO_LIB_DIR
|
||||
|
||||
# Stand in for the globals the entry script defines before sourcing the libs.
|
||||
_t_cco_setup() {
|
||||
TEST_TMPDIR="$(mktemp -d)"
|
||||
export TEST_TMPDIR
|
||||
|
||||
STATE_DIR="$TEST_TMPDIR/state"
|
||||
LOG_FILE="$STATE_DIR/compulsive-block.log"
|
||||
mkdir -p "$STATE_DIR"
|
||||
|
||||
AUTO_CLOSE_TIMEOUT_MINUTES=10
|
||||
AUTO_CLOSE_WARNING_MINUTES=2
|
||||
|
||||
declare -gA APP_TIMEOUT_MINUTES=(["beeper"]=20 ["signal-desktop"]=20)
|
||||
declare -gA APPS=(
|
||||
["beeper"]="$TEST_TMPDIR/bin/beeper"
|
||||
["signal-desktop"]="$TEST_TMPDIR/bin/signal-desktop"
|
||||
["discord"]="$TEST_TMPDIR/bin/discord"
|
||||
)
|
||||
declare -gA REAL_BINARIES=(
|
||||
["beeper"]="$TEST_TMPDIR/real/beepertexts"
|
||||
["signal-desktop"]="$TEST_TMPDIR/real/signal-desktop"
|
||||
["discord"]="$TEST_TMPDIR/bin/discord.orig"
|
||||
)
|
||||
declare -gA PROCESS_MATCH=(["discord"]="$TEST_TMPDIR/home/.config/discord/")
|
||||
|
||||
mkdir -p "$TEST_TMPDIR/bin" "$TEST_TMPDIR/real"
|
||||
|
||||
# notify() is defined in the entry script, which the tests never source.
|
||||
notify() { printf 'NOTIFY: %s | %s\n' "$1" "$2" >>"$TEST_TMPDIR/notifications"; }
|
||||
: >"$TEST_TMPDIR/notifications"
|
||||
|
||||
_t_cco_assert_fixture_complete
|
||||
}
|
||||
|
||||
# Every global above is read by the sourced lib, never by this file, so the
|
||||
# linter reports each one as unused (SC2034) and notify() as uncalled
|
||||
# (SC2329) — it cannot see across the `source` boundary the tests set up.
|
||||
# Referencing them here is not linter appeasement: it is a real fixture check.
|
||||
# A typo in one of these names would otherwise surface as a confusing unbound
|
||||
# variable from deep inside the code under test, or worse, as a silently
|
||||
# skipped assertion.
|
||||
_t_cco_assert_fixture_complete() {
|
||||
local missing=""
|
||||
[[ -n $LOG_FILE ]] || missing+=" LOG_FILE"
|
||||
[[ -n $AUTO_CLOSE_TIMEOUT_MINUTES ]] || missing+=" AUTO_CLOSE_TIMEOUT_MINUTES"
|
||||
[[ -n $AUTO_CLOSE_WARNING_MINUTES ]] || missing+=" AUTO_CLOSE_WARNING_MINUTES"
|
||||
[[ ${#APPS[@]} -eq 3 ]] || missing+=" APPS"
|
||||
[[ ${#REAL_BINARIES[@]} -eq 3 ]] || missing+=" REAL_BINARIES"
|
||||
[[ ${#APP_TIMEOUT_MINUTES[@]} -eq 2 ]] || missing+=" APP_TIMEOUT_MINUTES"
|
||||
[[ ${#PROCESS_MATCH[@]} -eq 1 ]] || missing+=" PROCESS_MATCH"
|
||||
|
||||
# Call notify() for real rather than probing it with `type -t`: block_app
|
||||
# routes every blocked launch through it, so a fixture whose notify is
|
||||
# broken would turn the notification assertions into silent no-ops. The
|
||||
# probe file is truncated afterwards so this call is not mistaken for one
|
||||
# made by the code under test.
|
||||
notify "fixture" "self-check"
|
||||
[[ -s "$TEST_TMPDIR/notifications" ]] || missing+=" notify"
|
||||
: >"$TEST_TMPDIR/notifications"
|
||||
|
||||
if [[ -n $missing ]]; then
|
||||
printf 'harness fixture incomplete:%s\n' "$missing" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
_t_cco_teardown() {
|
||||
[[ -n ${TEST_TMPDIR:-} && -d ${TEST_TMPDIR} ]] && rm -rf "$TEST_TMPDIR"
|
||||
}
|
||||
|
||||
_t_report() {
|
||||
printf '\n%s: %d passed, %d failed\n' "${1:-tests}" "$PASS" "$FAIL"
|
||||
[[ $FAIL -eq 0 ]]
|
||||
}
|
||||
@ -1,12 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs every leechblock lib test. Used directly as the coverage subject:
|
||||
# Runs every digital_wellbeing lib test. Used directly as the coverage subject:
|
||||
# meta/scripts/shell_coverage.sh wants the test script itself, not `bash <it>`.
|
||||
#
|
||||
# The glob is test_*.sh, NOT one prefix per split: this directory holds suites
|
||||
# for several entry scripts (leechblock, block_compulsive_opening, ...), and a
|
||||
# prefix glob silently skips every suite added after it — including in the CI
|
||||
# discovery step, which runs this file.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
rc=0
|
||||
for t in "$HERE"/test_leechblock_*.sh; do
|
||||
for t in "$HERE"/test_*.sh; do
|
||||
printf '\n=== %s ===\n' "$(basename "$t")"
|
||||
# Each suite exits non-zero on failure; keep going so one red suite does not
|
||||
# hide the state of the others, then fail the run as a whole.
|
||||
|
||||
@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env bash
|
||||
# Covers lib/cco_state.sh — the logic that decides whether a launch is allowed.
|
||||
#
|
||||
# This is the whole point of the tool: was_opened_this_hour deciding wrong in
|
||||
# either direction is the failure that matters. Too permissive and the blocker
|
||||
# does nothing; too strict and a legitimately-closed app can never be reopened.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=cco_harness.sh
|
||||
. "$HERE/cco_harness.sh"
|
||||
# shellcheck source=../cco_state.sh
|
||||
. "$CCO_LIB_DIR/cco_state.sh"
|
||||
|
||||
_t_cco_setup
|
||||
trap _t_cco_teardown EXIT
|
||||
|
||||
printf 'get_hour_key: a stable YYYY-MM-DD-HH stamp\n'
|
||||
hour="$(get_hour_key)"
|
||||
if [[ $hour =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}$ ]]; then
|
||||
_t_pass "the hour key is YYYY-MM-DD-HH"
|
||||
else
|
||||
_t_fail "the hour key is YYYY-MM-DD-HH (got '$hour')"
|
||||
fi
|
||||
_t_eq "$hour" "$(get_hour_key)" "two calls in the same hour agree"
|
||||
|
||||
printf '\nget_state_file: one file per app, under STATE_DIR\n'
|
||||
_t_eq "$STATE_DIR/discord.lastopen" "$(get_state_file discord)" "the state path is derived from the app name"
|
||||
_t_eq "$STATE_DIR/discord.running" "$(get_running_file discord)" "the running-state path is separate from the lastopen path"
|
||||
|
||||
printf '\nwas_opened_this_hour: the core allow/block decision\n'
|
||||
rm -f "$STATE_DIR/discord.lastopen"
|
||||
if was_opened_this_hour discord; then
|
||||
_t_fail "a fresh app is not yet opened this hour"
|
||||
else
|
||||
_t_pass "a fresh app is not yet opened this hour"
|
||||
fi
|
||||
|
||||
record_opening discord >/dev/null 2>&1
|
||||
if was_opened_this_hour discord; then
|
||||
_t_pass "after record_opening the app counts as opened"
|
||||
else
|
||||
_t_fail "after record_opening the app counts as opened"
|
||||
fi
|
||||
|
||||
printf '\nwas_opened_this_hour: a stale hour must NOT keep blocking\n'
|
||||
# The bug that would matter most: if a previous hour's stamp still blocked, an
|
||||
# app could never be reopened. Write a deliberately old stamp.
|
||||
echo "2000-01-01-00" >"$STATE_DIR/discord.lastopen"
|
||||
if was_opened_this_hour discord; then
|
||||
_t_fail "a previous hour's stamp must not block the current hour"
|
||||
else
|
||||
_t_pass "a previous hour's stamp does not block the current hour"
|
||||
fi
|
||||
|
||||
printf '\nwas_opened_this_hour: an unreadable/empty stamp allows the launch\n'
|
||||
: >"$STATE_DIR/discord.lastopen"
|
||||
if was_opened_this_hour discord; then
|
||||
_t_fail "an empty state file must not block"
|
||||
else
|
||||
_t_pass "an empty state file does not block"
|
||||
fi
|
||||
|
||||
printf '\nrecord_opening: writes exactly the current hour\n'
|
||||
rm -f "$STATE_DIR/beeper.lastopen"
|
||||
record_opening beeper >/dev/null 2>&1
|
||||
_t_eq "$(get_hour_key)" "$(cat "$STATE_DIR/beeper.lastopen")" "the stamp written is the current hour key"
|
||||
|
||||
printf '\nblock_app: notifies the user\n'
|
||||
: >"$TEST_TMPDIR/notifications"
|
||||
block_app discord >/dev/null 2>&1
|
||||
_t_has "$(cat "$TEST_TMPDIR/notifications")" "Blocked" "blocking sends a desktop notification"
|
||||
|
||||
printf '\nis_autoclose_suspended: only todays marker counts\n'
|
||||
rm -f "$STATE_DIR/discord.suspend-autoclose"
|
||||
if is_autoclose_suspended discord; then
|
||||
_t_fail "no marker means not suspended"
|
||||
else
|
||||
_t_pass "no marker means not suspended"
|
||||
fi
|
||||
|
||||
printf '%(%Y-%m-%d)T' -1 >"$STATE_DIR/discord.suspend-autoclose"
|
||||
if is_autoclose_suspended discord; then
|
||||
_t_pass "todays marker suspends auto-close"
|
||||
else
|
||||
_t_fail "todays marker suspends auto-close"
|
||||
fi
|
||||
|
||||
echo "1999-12-31" >"$STATE_DIR/discord.suspend-autoclose"
|
||||
if is_autoclose_suspended discord; then
|
||||
_t_fail "a stale marker must not suspend auto-close"
|
||||
else
|
||||
_t_pass "a stale marker does not suspend auto-close"
|
||||
fi
|
||||
if [[ -f "$STATE_DIR/discord.suspend-autoclose" ]]; then
|
||||
_t_fail "a stale marker is cleaned up on detection"
|
||||
else
|
||||
_t_pass "a stale marker is cleaned up on detection"
|
||||
fi
|
||||
|
||||
printf '\nget_real_binary: only reports a binary once the wrapper is installed\n'
|
||||
rm -f "$TEST_TMPDIR/bin/beeper.orig"
|
||||
if get_real_binary beeper >/dev/null 2>&1; then
|
||||
_t_fail "an unwrapped app reports no real binary"
|
||||
else
|
||||
_t_pass "an unwrapped app reports no real binary"
|
||||
fi
|
||||
|
||||
: >"$TEST_TMPDIR/bin/beeper.orig"
|
||||
_t_eq "$TEST_TMPDIR/real/beepertexts" "$(get_real_binary beeper)" "a wrapped app resolves to its real binary"
|
||||
|
||||
printf '\nlog_message: appends to the log and echoes to stderr\n'
|
||||
: >"$LOG_FILE"
|
||||
log_message "hello from the test" 2>/dev/null
|
||||
_t_has "$(cat "$LOG_FILE")" "hello from the test" "the message reaches the log file"
|
||||
|
||||
printf '\nensure_state_dir: creates STATE_DIR when it is missing\n'
|
||||
rm -rf "$STATE_DIR"
|
||||
ensure_state_dir
|
||||
if [[ -d $STATE_DIR ]]; then
|
||||
_t_pass "a missing state directory is created"
|
||||
else
|
||||
_t_fail "a missing state directory is created"
|
||||
fi
|
||||
# Idempotent: the real script calls it on every wrapper launch.
|
||||
ensure_state_dir
|
||||
_t_pass "calling it again on an existing directory is harmless"
|
||||
|
||||
printf '\ncleanup_stale_running_state: clears state when nothing is running\n'
|
||||
running="$(get_running_file discord)"
|
||||
echo "999999 123" >"$running"
|
||||
# PROCESS_MATCH points at a path no process can match, so this is the
|
||||
# "app already exited" case.
|
||||
cleanup_stale_running_state discord 2>/dev/null
|
||||
if [[ -f $running ]]; then
|
||||
_t_fail "a running-state file for a dead process is removed"
|
||||
else
|
||||
_t_pass "a running-state file for a dead process is removed"
|
||||
fi
|
||||
|
||||
printf '\ncleanup_stale_running_state: no running file is a no-op\n'
|
||||
# The early return. It must not fall through to the pgrep path, which on a
|
||||
# machine where the app IS running would otherwise be consulted for nothing.
|
||||
rm -f "$running"
|
||||
if (cleanup_stale_running_state discord); then
|
||||
_t_pass "a missing running-state file returns success without probing"
|
||||
else
|
||||
_t_fail "a missing running-state file returns success without probing"
|
||||
fi
|
||||
|
||||
_t_report "test_cco_state"
|
||||
@ -32,6 +32,21 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# shellcheck source=lib/nl_commands.sh
|
||||
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/nl_commands.sh"
|
||||
|
||||
# shellcheck source=lib/nl_config.sh
|
||||
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/nl_config.sh"
|
||||
|
||||
# shellcheck source=lib/nl_units.sh
|
||||
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/nl_units.sh"
|
||||
|
||||
# shellcheck source=lib/nl_unlock.sh
|
||||
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/nl_unlock.sh"
|
||||
|
||||
# shellcheck source=lib/nl_enter.sh
|
||||
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/nl_enter.sh"
|
||||
|
||||
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
|
||||
# shellcheck source=../../lib/common.sh
|
||||
source "$SCRIPT_DIR/../../lib/common.sh"
|
||||
@ -55,715 +70,18 @@ readonly MANAGED_BANNER="# Managed by setup_night_lockdown.sh — do not edit by
|
||||
# Hardware / environment detection (run at install time, written into the conf)
|
||||
# =============================================================================
|
||||
|
||||
# Detect ALSA card indices that expose a 'Master' control (space-separated).
|
||||
detect_alsa_cards() {
|
||||
local card cards=""
|
||||
for card in 0 1 2 3 4 5 6; do
|
||||
if amixer -c "$card" scontrols 2>/dev/null | grep -q "'Master'"; then
|
||||
cards+="${card} "
|
||||
fi
|
||||
done
|
||||
# Trim trailing space.
|
||||
echo "${cards% }"
|
||||
}
|
||||
|
||||
# Write /etc/night-lockdown.conf with values detected for THIS machine.
|
||||
write_config() {
|
||||
local user uid alsa_cards
|
||||
user="$ACTUAL_USER"
|
||||
uid="$(id -u "$user")"
|
||||
alsa_cards="$(detect_alsa_cards)"
|
||||
|
||||
log_info "Writing config to $CONF_FILE (user=$user uid=$uid alsa_cards='$alsa_cards')"
|
||||
cat >"$CONF_FILE" <<EOF
|
||||
$MANAGED_BANNER
|
||||
# Desktop user whose GUI session is torn down at lockdown.
|
||||
LOCK_USER="$user"
|
||||
LOCK_UID="$uid"
|
||||
|
||||
# ALSA card indices with a 'Master' control, muted at lockdown (best-effort).
|
||||
ALSA_CARDS="$alsa_cards"
|
||||
|
||||
# Kill all RGB via OpenRGB. Detected here: 2x ENE DRAM (RGB RAM, i2c 0x71/0x73),
|
||||
# ZOTAC RTX 3090 (GPU), ASRock B650M Pro RS (USB Polychrome 26ce:01a2).
|
||||
RGB_ENABLE="1"
|
||||
|
||||
# How to turn the lighting off. Use static + black, NOT the "off" mode:
|
||||
# - the ZOTAC GPU has no "Off" mode at all (its modes are Static/Breath/...);
|
||||
# - the ASRock board lists "Off" but silently ignores it (mode stayed Rainbow),
|
||||
# while static+black moves it to Static and goes dark.
|
||||
# All four devices support Static, so this one form works everywhere. Verified:
|
||||
# 'openrgb --mode static --color 000000' -> all 4 devices report ACTIVE: Static.
|
||||
RGB_OFF_MODE="static"
|
||||
RGB_OFF_COLOR="000000"
|
||||
|
||||
# HOME that openrgb runs with: it keeps its config under its own HOME, and
|
||||
# systemd (HOME=/root) vs sudo (HOME=/home/USER) would otherwise disagree about
|
||||
# where that config lives, so pin it for both directions.
|
||||
RGB_HOME="/root"
|
||||
|
||||
# User systemd units (graphical-session-bound) stopped at lockdown, space-sep.
|
||||
MONITORED_USER_UNITS="control-from-mobile.service"
|
||||
|
||||
# GUI tray processes (not systemd units) killed at lockdown, space-separated.
|
||||
MONITORED_PROCS="aw-qt"
|
||||
|
||||
# Text console to blank at lockdown. Stopping lightdm hands the VT back to fbcon,
|
||||
# which unblanks and prints kernel/systemd log spam instead of showing darkness.
|
||||
CONSOLE_TTY="/dev/tty1"
|
||||
|
||||
# How hard to blank the console (/sys/class/graphics/fbN/blank value):
|
||||
# 1 = FB_BLANK_NORMAL — screen black, monitor keeps its signal. SAFE.
|
||||
# 4 = FB_BLANK_POWERDOWN — DPMS off, monitor drops to standby.
|
||||
# Do NOT use 4 here: DisplayPort drops its link when powered down, and the GPU
|
||||
# then sees the connector as disconnected and will not re-train it on wake —
|
||||
# DP-0 vanished from xrandr and needed the cable physically re-plugged. HDMI
|
||||
# tolerates it, DP does not. 1 still gives a fully black screen, which is the
|
||||
# whole point, without touching the link.
|
||||
CONSOLE_BLANK_MODE="1"
|
||||
|
||||
# Never start the morning alarm earlier than lockdown-entry + this many hours,
|
||||
# even though the unlock timer itself still fires on its normal staggered
|
||||
# schedule (05:00/05:15/05:30/06:00/07:00). A late lockdown entry (e.g. 23:00
|
||||
# instead of the usual 21:00) must not still wake you 6h later.
|
||||
MIN_WAKE_AFTER_LOCKDOWN_HOURS="8"
|
||||
|
||||
# autorandr profile to restore after the GUI comes back up. Create it once with
|
||||
# 'autorandr --save default' while all monitors are connected and arranged the
|
||||
# way you want; the unlock script re-applies it so a DisplayPort link that
|
||||
# didn't re-enumerate cleanly doesn't require a manual xrandr/replug.
|
||||
AUTORANDR_PROFILE="default"
|
||||
|
||||
# Cap CPU/GPU power draw for the night as a safety net against anything left
|
||||
# running headless overnight (interactive GPU/CPU load dies with the GUI
|
||||
# teardown above, but a systemd service — e.g. ollama serving a request — does
|
||||
# not). Set to "0" to disable without touching the enter/unlock scripts.
|
||||
POWER_SAVE_ENABLE="1"
|
||||
|
||||
# AMD amd-pstate-epp hint applied to every core at lockdown (this machine is
|
||||
# Ryzen, not Intel, so intel_pstate/no_turbo does not apply). One of: default,
|
||||
# performance, balance_performance, balance_power, power, custom.
|
||||
CPU_EPP_NIGHT="power"
|
||||
|
||||
# nvidia-smi power limit (watts) applied at lockdown. Set to this card's
|
||||
# reported power.min_limit (100W on the RTX 3090 here) so a runaway overnight
|
||||
# CUDA job is bounded, not eliminated — persistence mode is deliberately left
|
||||
# alone so any legitimate headless GPU service keeps working, just slower.
|
||||
GPU_POWER_LIMIT_NIGHT_WATTS="100"
|
||||
|
||||
# Fully unbind the GPU from the PCI bus at lockdown (unload nvidia kernel
|
||||
# modules + PCI remove), rescanned back at unlock. Far more aggressive than
|
||||
# the power-limit cap above: recovers more idle wattage, but modprobe -r can
|
||||
# hang if anything still references the device, and a botched unbind might
|
||||
# need a hard power-cycle to recover -- which WOULD take every container down
|
||||
# with it (the one thing night-lockdown exists to prevent). Default OFF and
|
||||
# deliberately left off: the first real run of this is an uncorroborated test
|
||||
# on this exact kernel/driver, not a dress rehearsal -- nothing can safely
|
||||
# test it without also tearing down the GUI it runs under.
|
||||
GPU_UNBIND_ENABLE="0"
|
||||
EOF
|
||||
chmod 0644 "$CONF_FILE"
|
||||
|
||||
# This heredoc is intentionally UNQUOTED so the detected values above
|
||||
# interpolate — which also means a stray backtick or $ anywhere in it
|
||||
# (even inside a comment) gets executed/expanded and its output injected
|
||||
# into the file. That has bitten twice, and a corrupted config makes the
|
||||
# lock script fail to source it and silently skip steps. Fail loudly here
|
||||
# instead of shipping a broken config.
|
||||
if ! bash -n "$CONF_FILE" 2>/dev/null; then
|
||||
log_error "Generated $CONF_FILE is not valid shell — refusing to continue."
|
||||
log_error "Check write_config() for backticks or \$ in the heredoc."
|
||||
bash -n "$CONF_FILE" || true
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# The lock action — installed to $ENTER_SCRIPT
|
||||
# =============================================================================
|
||||
|
||||
install_enter_script() {
|
||||
log_info "Installing lock action to $ENTER_SCRIPT"
|
||||
cat >"$ENTER_SCRIPT" <<'ENTER_EOF'
|
||||
#!/bin/bash
|
||||
# Managed by setup_night_lockdown.sh — do not edit by hand.
|
||||
#
|
||||
# Enter night lockdown: tear down the user GUI and mask the TTY login surface so
|
||||
# the machine is unusable from the keyboard, while every background server keeps
|
||||
# running. Reversed by night-lockdown-unlock.sh (05:00 timer or SSH recovery).
|
||||
# All steps are best-effort and logged; DRY_RUN=1 logs intended actions only.
|
||||
set -euo pipefail
|
||||
|
||||
readonly CONF_FILE="/etc/night-lockdown.conf"
|
||||
readonly STATE_DIR="/var/lib/night-lockdown"
|
||||
readonly STATE_FILE="$STATE_DIR/state"
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
[[ -r "$CONF_FILE" ]] && source "$CONF_FILE"
|
||||
LOCK_USER="${LOCK_USER:-}"
|
||||
LOCK_UID="${LOCK_UID:-}"
|
||||
ALSA_CARDS="${ALSA_CARDS:-}"
|
||||
RGB_ENABLE="${RGB_ENABLE:-1}"
|
||||
MONITORED_USER_UNITS="${MONITORED_USER_UNITS:-}"
|
||||
MONITORED_PROCS="${MONITORED_PROCS:-}"
|
||||
MIN_WAKE_AFTER_LOCKDOWN_HOURS="${MIN_WAKE_AFTER_LOCKDOWN_HOURS:-8}"
|
||||
CONSOLE_TTY="${CONSOLE_TTY:-/dev/tty1}"
|
||||
CONSOLE_BLANK_MODE="${CONSOLE_BLANK_MODE:-1}"
|
||||
POWER_SAVE_ENABLE="${POWER_SAVE_ENABLE:-1}"
|
||||
CPU_EPP_NIGHT="${CPU_EPP_NIGHT:-power}"
|
||||
GPU_POWER_LIMIT_NIGHT_WATTS="${GPU_POWER_LIMIT_NIGHT_WATTS:-100}"
|
||||
GPU_UNBIND_ENABLE="${GPU_UNBIND_ENABLE:-0}"
|
||||
DRY_RUN="${DRY_RUN:-}"
|
||||
|
||||
logg() { logger -t night-lockdown "$*"; printf 'night-lockdown: %s\n' "$*"; }
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN NOTE: log-only — lightdm is never actually stopped and the"
|
||||
logg "DRY_RUN NOTE: console framebuffer is never actually touched. This CANNOT"
|
||||
logg "DRY_RUN NOTE: exercise the blank-vs-VT-switch timing race (bug: visible"
|
||||
logg "DRY_RUN NOTE: console text). A clean DRY_RUN run is NOT proof that fix"
|
||||
logg "DRY_RUN NOTE: works — only a real run (DRY_RUN unset) validates it."
|
||||
logg "DRY_RUN NOTE: The CPU EPP write, nvidia-smi power-limit cap, and (if"
|
||||
logg "DRY_RUN NOTE: enabled) GPU PCI-unbind are also never actually applied"
|
||||
logg "DRY_RUN NOTE: under DRY_RUN — real-hardware timing/driver behavior for"
|
||||
logg "DRY_RUN NOTE: those is unverified until a real run."
|
||||
fi
|
||||
|
||||
# Run a command best-effort: log-only under DRY_RUN, never abort the lockdown.
|
||||
run() {
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: $*"
|
||||
return 0
|
||||
fi
|
||||
if ! "$@"; then
|
||||
logg "WARN: command failed (continuing): $*"
|
||||
fi
|
||||
}
|
||||
|
||||
# Run a command as the desktop user inside their session bus.
|
||||
run_as_user() {
|
||||
[[ -n "$LOCK_USER" && -n "$LOCK_UID" && -d "/run/user/$LOCK_UID" ]] || return 0
|
||||
run sudo -u "$LOCK_USER" env "XDG_RUNTIME_DIR=/run/user/$LOCK_UID" "$@"
|
||||
}
|
||||
|
||||
# Silence everything that prints to the text console. Once lightdm stops, the VT
|
||||
# reverts to fbcon and any kernel/systemd message lights the screen back up.
|
||||
silence_console() {
|
||||
# systemd status messages ("Starting/Stopped ...") -> off. RTMIN+20 re-enables.
|
||||
run kill -s RTMIN+21 1
|
||||
# Kernel messages -> console. Save the current printk so unlock can restore it.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
cat /proc/sys/kernel/printk >"$STATE_DIR/printk.prev" 2>/dev/null || true
|
||||
fi
|
||||
run sysctl -q -w "kernel.printk=1 4 1 4"
|
||||
}
|
||||
|
||||
# Force the console dark — black screen, but WITHOUT DPMS power management.
|
||||
# Powering the output down (FB_BLANK_POWERDOWN / setterm --powersave powerdown)
|
||||
# makes DisplayPort drop its link; the GPU then reports the connector
|
||||
# disconnected and never re-trains it, so the monitor is gone from xrandr until
|
||||
# the cable is physically re-plugged. Blanking alone is enough to go black.
|
||||
blank_console() {
|
||||
local fb
|
||||
for fb in /sys/class/graphics/fb*/blank; do
|
||||
[[ -e "$fb" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write $CONSOLE_BLANK_MODE (blank) > $fb"
|
||||
continue
|
||||
fi
|
||||
echo "$CONSOLE_BLANK_MODE" >"$fb" 2>/dev/null || logg "WARN: could not blank $fb"
|
||||
done
|
||||
# setterm emits escape sequences on stdout; from a systemd service stdout is
|
||||
# the journal, so aim it at the VT explicitly. --powersave off keeps DPMS out
|
||||
# of it so the DP link survives.
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would force console blank (no DPMS) on $CONSOLE_TTY"
|
||||
elif [[ -w "$CONSOLE_TTY" ]]; then
|
||||
setterm --term linux --blank force --powersave off \
|
||||
>"$CONSOLE_TTY" 2>/dev/null || logg "WARN: setterm blank failed"
|
||||
fi
|
||||
}
|
||||
|
||||
mkdir -p "$STATE_DIR"
|
||||
|
||||
# 1. Idempotency — entering lockdown when already locked is a safe no-op.
|
||||
if [[ "$(cat "$STATE_FILE" 2>/dev/null || echo UNLOCKED)" == "LOCKED" ]]; then
|
||||
logg "already LOCKED — nothing to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
logg "entering night lockdown"
|
||||
|
||||
# 2. RGB off (RAM + board + GPU), remembering the current lighting first.
|
||||
#
|
||||
# Do NOT gate this on `openrgb --list-devices`: that call is broken in the
|
||||
# installed openrgb-git build — it returns in ~70ms, before async detection
|
||||
# finishes, so it always reports zero devices. (That false "no controllers"
|
||||
# reading is why this step silently no-op'd.) The fix was to install stable
|
||||
# openrgb 1.0rc3 from extra, whose CLI detects properly (~1.9s) before acting.
|
||||
if [[ "$RGB_ENABLE" == "1" ]] && command -v openrgb >/dev/null 2>&1; then
|
||||
run env HOME="$RGB_HOME" openrgb --mode "$RGB_OFF_MODE" --color "$RGB_OFF_COLOR"
|
||||
fi
|
||||
|
||||
# 2b. Cap CPU/GPU power draw for the night. Save the pre-lockdown values first
|
||||
# so unlock restores exactly what was there, not a hardcoded "default" —
|
||||
# the user may have changed either away from factory settings.
|
||||
# Capture is guarded on the .prev file NOT already existing: this step
|
||||
# runs before state is written LOCKED (step 5), so a kill between here and
|
||||
# there leaves state UNLOCKED and the 30-min curfew check re-invokes this
|
||||
# whole script. Without the guard, that re-run would recapture "prev" from
|
||||
# the already-applied NIGHT value, permanently stranding the machine in
|
||||
# night power-save mode. unlock deletes the .prev file after a successful
|
||||
# restore, so a normal (non-crashed) cycle still captures fresh each night.
|
||||
if [[ "$POWER_SAVE_ENABLE" == "1" ]]; then
|
||||
if [[ -f /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference ]]; then
|
||||
if [[ "$DRY_RUN" != "1" && ! -f "$STATE_DIR/cpu_epp.prev" ]]; then
|
||||
cat /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference \
|
||||
>"$STATE_DIR/cpu_epp.prev" 2>/dev/null || true
|
||||
fi
|
||||
for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
|
||||
[[ -e "$epp_file" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write $CPU_EPP_NIGHT > $epp_file"
|
||||
else
|
||||
echo "$CPU_EPP_NIGHT" >"$epp_file" 2>/dev/null || logg "WARN: could not set EPP on $epp_file"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if command -v nvidia-smi >/dev/null 2>&1; then
|
||||
if [[ "$DRY_RUN" != "1" && ! -f "$STATE_DIR/gpu_power_limit_watts.prev" ]]; then
|
||||
nvidia-smi --query-gpu=power.limit --format=csv,noheader,nounits \
|
||||
>"$STATE_DIR/gpu_power_limit_watts.prev" 2>/dev/null || true
|
||||
fi
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: timeout 10 nvidia-smi -pl $GPU_POWER_LIMIT_NIGHT_WATTS"
|
||||
else
|
||||
run timeout 10 nvidia-smi -pl "$GPU_POWER_LIMIT_NIGHT_WATTS"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Mute audio (best-effort). The session teardown below silences apps anyway;
|
||||
# this covers any direct-ALSA sound. PipeWire is intentionally NOT touched, so
|
||||
# the morning unlock cannot be defeated by a persisted wireplumber mute.
|
||||
for card in $ALSA_CARDS; do
|
||||
command -v amixer >/dev/null 2>&1 && run amixer -c "$card" -q set Master mute
|
||||
done
|
||||
|
||||
# 4. Stop GUI-bound user units + tray apps (they die with X anyway; be tidy).
|
||||
for unit in $MONITORED_USER_UNITS; do
|
||||
run_as_user systemctl --user stop "$unit"
|
||||
done
|
||||
for proc in $MONITORED_PROCS; do
|
||||
# Only kill if actually running — pkill exits 1 on no-match, which would log
|
||||
# a misleading "command failed" WARN every night for an app that isn't up.
|
||||
if [[ -n "$LOCK_USER" ]] && pgrep -u "$LOCK_USER" -x "$proc" >/dev/null 2>&1; then
|
||||
run pkill -u "$LOCK_USER" -x "$proc"
|
||||
fi
|
||||
done
|
||||
|
||||
# 5. Persist the LOCKED intent BEFORE the session-killing teardown. Stopping
|
||||
# lightdm tears down the graphical session that this very process runs in, so
|
||||
# if we wrote state AFTER the teardown, a kill mid-teardown would leave state
|
||||
# at UNLOCKED — and the unlock path (which no-ops when UNLOCKED) would then
|
||||
# fail to restore, stranding the machine. Write intent first; any unlock
|
||||
# (05:00 timer, dead-man, or manual) then correctly restores.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
echo LOCKED >"$STATE_FILE"
|
||||
lockdown_epoch="$(date +%s)"
|
||||
echo "$lockdown_epoch" >"$STATE_DIR/locked_at_epoch"
|
||||
|
||||
# 5a. Schedule a one-shot wake-floor trigger for exactly
|
||||
# lockdown_epoch + MIN_WAKE_AFTER_LOCKDOWN_HOURS. The staggered
|
||||
# 05:00/05:15/05:30/06:00/07:00 unlock triggers are a fixed list sized
|
||||
# for the usual shutdown hours (~21:00-23:00), but the shutdown hour
|
||||
# itself is configurable (/etc/shutdown-schedule.conf) and changes
|
||||
# dynamically (see the sick-day feature). If lockdown ever starts late
|
||||
# enough that the floor lands after every remaining fixed trigger, the
|
||||
# alarm would otherwise silently never fire that morning. This
|
||||
# transient timer fires at the exact floor moment for THIS lockdown
|
||||
# regardless of what time it actually started, re-running the
|
||||
# (idempotent, self-dedup'd) unlock script, which is where the alarm
|
||||
# is actually attempted.
|
||||
floor_epoch=$((lockdown_epoch + MIN_WAKE_AFTER_LOCKDOWN_HOURS * 3600))
|
||||
floor_cal="$(date -d "@$floor_epoch" '+%Y-%m-%d %H:%M:%S')"
|
||||
run systemd-run --unit=night-lockdown-wake-floor --collect \
|
||||
--on-calendar="$floor_cal" /usr/local/bin/night-lockdown-unlock.sh
|
||||
else
|
||||
logg "DRY_RUN: would schedule a one-shot wake-floor trigger ~${MIN_WAKE_AFTER_LOCKDOWN_HOURS}h from now"
|
||||
fi
|
||||
|
||||
# 6a. Silence the console BEFORE stopping the GUI, so the teardown itself
|
||||
# ("Stopping Light Display Manager...") does not print onto the VT.
|
||||
silence_console
|
||||
|
||||
# 6. Mask the login surface BEFORE stopping the GUI, so logind cannot spawn a
|
||||
# getty into the gap. Mask ONLY getty@.service: autovt@.service is an alias
|
||||
# symlink to it, so masking getty@ already makes autovt@ttyN resolve to
|
||||
# masked ("Unit autovt@ttyN.service is masked" — logind cannot spawn a VT
|
||||
# login). Passing autovt@ to mask instead FAILS ("File
|
||||
# /etc/systemd/system/autovt@.service already exists and is a symlink"),
|
||||
# which is what produced the nightly WARN. Masks are /dev/null symlinks that
|
||||
# persist across reboot; the unlock path unmasks them.
|
||||
run systemctl mask getty@.service
|
||||
run systemctl stop 'getty@*.service'
|
||||
|
||||
# 7. Stop the GUI while continuously re-blanking the console in the
|
||||
# background. Activating a VT (which happens somewhere mid-way through the
|
||||
# GUI stop, not only once "systemctl stop" fully returns) makes fbcon
|
||||
# redraw/unblank as part of the switch, so a single blank-after-the-fact
|
||||
# call leaves a gap showing whatever was last on the console (old
|
||||
# kernel/systemd text) for however long the rest of the stop sequence
|
||||
# takes. Keep forcing it dark for the whole teardown instead of waiting.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
(
|
||||
while :; do
|
||||
blank_console
|
||||
sleep 0.1
|
||||
done
|
||||
) &
|
||||
BLANK_POLLER_PID=$!
|
||||
fi
|
||||
run systemctl stop lightdm.service
|
||||
if [[ -n "${BLANK_POLLER_PID:-}" ]]; then
|
||||
kill "$BLANK_POLLER_PID" 2>/dev/null || true
|
||||
wait "$BLANK_POLLER_PID" 2>/dev/null || true
|
||||
unset BLANK_POLLER_PID
|
||||
fi
|
||||
|
||||
# 8. Final guaranteed blank now that the GUI is fully down.
|
||||
blank_console
|
||||
|
||||
# 9. Optionally unbind the GPU entirely (default OFF — see GPU_UNBIND_ENABLE
|
||||
# comment in night-lockdown.conf for the risk tradeoff). Only ever runs
|
||||
# after the GUI is torn down, since nothing interactive needs the GPU at
|
||||
# this point. Timeout-guarded: modprobe -r can hang if anything still
|
||||
# references the device, and a hang here must not block the rest of
|
||||
# lockdown.
|
||||
if [[ "$GPU_UNBIND_ENABLE" == "1" ]] && command -v nvidia-smi >/dev/null 2>&1; then
|
||||
gpu_pci="$(lspci -d 10de: 2>/dev/null | grep -i 'VGA\|3D' | awk '{print $1}' | head -1)"
|
||||
if [[ -z "$gpu_pci" ]]; then
|
||||
logg "WARN: GPU_UNBIND_ENABLE=1 but no nvidia PCI device found"
|
||||
elif [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would unload nvidia modules and remove PCI device 0000:$gpu_pci"
|
||||
elif timeout 20 modprobe -r nvidia_uvm nvidia_drm nvidia_modeset nvidia 2>&1 | logger -t night-lockdown; then
|
||||
if echo 1 >"/sys/bus/pci/devices/0000:$gpu_pci/remove" 2>/dev/null; then
|
||||
logg "GPU unbound (0000:$gpu_pci removed from PCI bus)"
|
||||
# Unloading nvidia_drm / the PCI remove can surface a fallback
|
||||
# framebuffer that isn't blanked -- same failure class the
|
||||
# continuous re-blank during the lightdm stop (above) exists to
|
||||
# close, just triggered by module unload instead of a VT switch.
|
||||
blank_console
|
||||
else
|
||||
logg "WARN: modules unloaded but PCI remove failed for 0000:$gpu_pci"
|
||||
fi
|
||||
else
|
||||
logg "WARN: modprobe -r timed out or failed -- GPU left bound, skipping unbind"
|
||||
fi
|
||||
fi
|
||||
|
||||
logg "night lockdown active — servers up, GUI down, login surface masked, console dark"
|
||||
ENTER_EOF
|
||||
chmod 0755 "$ENTER_SCRIPT"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# The reversal — installed to $UNLOCK_SCRIPT
|
||||
# =============================================================================
|
||||
|
||||
install_unlock_script() {
|
||||
log_info "Installing reversal to $UNLOCK_SCRIPT"
|
||||
cat >"$UNLOCK_SCRIPT" <<'UNLOCK_EOF'
|
||||
#!/bin/bash
|
||||
# Managed by setup_night_lockdown.sh — do not edit by hand.
|
||||
#
|
||||
# Lift night lockdown: unmask the login surface, restart the GUI, unmute audio.
|
||||
# Idempotent (safe to fire from the 5 staggered morning triggers and manual runs)
|
||||
# and deliberately independent of the shutdown fortress, so it can always run.
|
||||
set -euo pipefail
|
||||
|
||||
readonly CONF_FILE="/etc/night-lockdown.conf"
|
||||
readonly STATE_DIR="/var/lib/night-lockdown"
|
||||
readonly STATE_FILE="$STATE_DIR/state"
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
[[ -r "$CONF_FILE" ]] && source "$CONF_FILE"
|
||||
ALSA_CARDS="${ALSA_CARDS:-}"
|
||||
LOCK_USER="${LOCK_USER:-}"
|
||||
LOCK_UID="${LOCK_UID:-}"
|
||||
MIN_WAKE_AFTER_LOCKDOWN_HOURS="${MIN_WAKE_AFTER_LOCKDOWN_HOURS:-8}"
|
||||
AUTORANDR_PROFILE="${AUTORANDR_PROFILE:-default}"
|
||||
CONSOLE_TTY="${CONSOLE_TTY:-/dev/tty1}"
|
||||
RGB_ENABLE="${RGB_ENABLE:-1}"
|
||||
RGB_OFF_MODE="${RGB_OFF_MODE:-static}"
|
||||
RGB_OFF_COLOR="${RGB_OFF_COLOR:-000000}"
|
||||
RGB_HOME="${RGB_HOME:-/root}"
|
||||
POWER_SAVE_ENABLE="${POWER_SAVE_ENABLE:-1}"
|
||||
GPU_UNBIND_ENABLE="${GPU_UNBIND_ENABLE:-0}"
|
||||
DRY_RUN="${DRY_RUN:-}"
|
||||
|
||||
logg() { logger -t night-lockdown "$*"; printf 'night-lockdown: %s\n' "$*"; }
|
||||
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN NOTE: log-only — lightdm is never actually started and"
|
||||
logg "DRY_RUN NOTE: autorandr is never actually invoked. This CANNOT exercise"
|
||||
logg "DRY_RUN NOTE: the real DisplayPort reconnect or graphical-session wait."
|
||||
logg "DRY_RUN NOTE: A clean DRY_RUN run is NOT proof those work — only a real"
|
||||
logg "DRY_RUN NOTE: run (DRY_RUN unset) validates them. The alarm floor/dedup"
|
||||
logg "DRY_RUN NOTE: logic (locked_at_epoch) IS exercised"
|
||||
logg "DRY_RUN NOTE: faithfully here, since that part is pure calculation."
|
||||
logg "DRY_RUN NOTE: The CPU EPP / GPU power-limit restore and (if enabled)"
|
||||
logg "DRY_RUN NOTE: the PCI rescan are also never actually applied under"
|
||||
logg "DRY_RUN NOTE: DRY_RUN — real-hardware timing/driver behavior for"
|
||||
logg "DRY_RUN NOTE: those is unverified until a real run."
|
||||
fi
|
||||
|
||||
run() {
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: $*"
|
||||
return 0
|
||||
fi
|
||||
if ! "$@"; then
|
||||
logg "WARN: command failed (continuing): $*"
|
||||
fi
|
||||
}
|
||||
|
||||
# NOTE: this script used to also start morning-routine.service here, on a
|
||||
# fixed 05:00/05:15/05:30/06:00/07:00 ladder. wake-alarm-trigger.timer now
|
||||
# owns firing the alarm: it ticks every minute and fires at the time the
|
||||
# phone synced, so the alarm follows the phone instead of a hardcoded hour.
|
||||
# Keeping both meant a 07:00 alarm on a morning the phone said 08:00.
|
||||
|
||||
mkdir -p "$STATE_DIR"
|
||||
|
||||
# Idempotency — lifting when already unlocked is a safe no-op.
|
||||
if [[ "$(cat "$STATE_FILE" 2>/dev/null || echo UNLOCKED)" == "UNLOCKED" ]]; then
|
||||
logg "already UNLOCKED — nothing else to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
logg "lifting night lockdown"
|
||||
|
||||
# 0. Restore the console: unblank it and let kernel/systemd talk to it again.
|
||||
# Must happen even if everything below fails, or the machine would stay
|
||||
# permanently silent on the console after any unlock.
|
||||
restore_console() {
|
||||
local fb prev
|
||||
for fb in /sys/class/graphics/fb*/blank; do
|
||||
[[ -e "$fb" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write 0 (unblank) > $fb"
|
||||
continue
|
||||
fi
|
||||
echo 0 >"$fb" 2>/dev/null || true
|
||||
done
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would restore printk + systemd status messages"
|
||||
return 0
|
||||
fi
|
||||
[[ -w "$CONSOLE_TTY" ]] && setterm --term linux --blank poke --powersave off \
|
||||
>"$CONSOLE_TTY" 2>/dev/null
|
||||
if [[ -r "$STATE_DIR/printk.prev" ]]; then
|
||||
prev="$(cat "$STATE_DIR/printk.prev")"
|
||||
[[ -n "$prev" ]] && sysctl -q -w "kernel.printk=$prev" 2>/dev/null
|
||||
fi
|
||||
kill -s RTMIN+20 1 2>/dev/null || true # systemd: status messages back on
|
||||
}
|
||||
restore_console
|
||||
|
||||
# 1. Unmask the login surface (undo the persistent /dev/null mask). Only
|
||||
# getty@.service is ever masked; autovt@.service is just an alias to it.
|
||||
run systemctl unmask getty@.service
|
||||
|
||||
# 1a. If the GPU was unbound at lockdown, rescan the PCI bus to bring it back
|
||||
# before starting the GUI. Harmless no-op if nothing was removed. Polls
|
||||
# for the driver actually being ready (nvidia-smi succeeding) rather than
|
||||
# a fixed sleep -- starting lightdm against a GPU that hasn't finished
|
||||
# reprobing risks a failed X start, which (unlike a mis-enumerated
|
||||
# display) the autorandr retry loop above cannot recover from.
|
||||
if [[ "$GPU_UNBIND_ENABLE" == "1" ]]; then
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would rescan PCI bus and wait for the GPU driver to be ready"
|
||||
else
|
||||
echo 1 >/sys/bus/pci/rescan 2>/dev/null || logg "WARN: PCI rescan failed"
|
||||
gpu_ready=false
|
||||
for ((i = 0; i < 15; i++)); do
|
||||
if nvidia-smi >/dev/null 2>&1; then
|
||||
gpu_ready=true
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [[ "$gpu_ready" == true ]]; then
|
||||
logg "GPU driver ready after PCI rescan"
|
||||
else
|
||||
logg "WARN: GPU driver not ready after rescan + 15s -- starting GUI anyway"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Start the GUI — lightdm autologins back into i3/dwm.
|
||||
run systemctl start lightdm.service
|
||||
|
||||
# 2a. Reconnect/reconfigure displays. A DisplayPort link does not always
|
||||
# re-enumerate cleanly on its own after the console teardown, leaving a
|
||||
# monitor disconnected until someone runs xrandr by hand. Retry autorandr
|
||||
# for a bit while the session comes up instead. Requires a saved profile
|
||||
# ('autorandr --save default' run once while all monitors are connected).
|
||||
if [[ -n "$LOCK_USER" && -n "$LOCK_UID" ]] && command -v autorandr >/dev/null 2>&1; then
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run autorandr --change as $LOCK_USER"
|
||||
else
|
||||
autorandr_ok=false
|
||||
for ((i = 0; i < 15; i++)); do
|
||||
if sudo -u "$LOCK_USER" env "XDG_RUNTIME_DIR=/run/user/$LOCK_UID" DISPLAY=:0 \
|
||||
autorandr --change --default "$AUTORANDR_PROFILE" >/dev/null 2>&1; then
|
||||
autorandr_ok=true
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [[ "$autorandr_ok" == true ]]; then
|
||||
logg "autorandr: displays restored (profile '$AUTORANDR_PROFILE')"
|
||||
else
|
||||
logg "WARN: autorandr did not settle after retries — displays may need manual xrandr"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Restore audio (unmute the cards muted at lockdown).
|
||||
for card in $ALSA_CARDS; do
|
||||
command -v amixer >/dev/null 2>&1 && run amixer -c "$card" -q set Master unmute
|
||||
done
|
||||
|
||||
# 3b. Restore CPU EPP and GPU power limit to their pre-lockdown values (saved
|
||||
# by night-lockdown-enter.sh). Missing state file = enter never ran the
|
||||
# power-save step (e.g. it was disabled then) — nothing to restore.
|
||||
# Delete each .prev file after a successful (non-DRY_RUN) restore: enter's
|
||||
# capture is guarded on the file NOT existing (crash-safety, see its own
|
||||
# comment), so leaving a stale file here would freeze future captures to
|
||||
# tonight's value forever instead of tracking whatever the user's daytime
|
||||
# setting actually is.
|
||||
if [[ "$POWER_SAVE_ENABLE" == "1" ]]; then
|
||||
if [[ -r "$STATE_DIR/cpu_epp.prev" ]]; then
|
||||
prev_epp="$(cat "$STATE_DIR/cpu_epp.prev")"
|
||||
if [[ -n "$prev_epp" ]]; then
|
||||
for epp_file in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do
|
||||
[[ -e "$epp_file" ]] || continue
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would write $prev_epp > $epp_file"
|
||||
else
|
||||
echo "$prev_epp" >"$epp_file" 2>/dev/null || logg "WARN: could not restore EPP on $epp_file"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
[[ "$DRY_RUN" == "1" ]] || rm -f "$STATE_DIR/cpu_epp.prev"
|
||||
fi
|
||||
|
||||
if command -v nvidia-smi >/dev/null 2>&1 && [[ -r "$STATE_DIR/gpu_power_limit_watts.prev" ]]; then
|
||||
prev_watts="$(cat "$STATE_DIR/gpu_power_limit_watts.prev")"
|
||||
if [[ -n "$prev_watts" ]]; then
|
||||
if [[ "$DRY_RUN" == "1" ]]; then
|
||||
logg "DRY_RUN: would run: timeout 10 nvidia-smi -pl $prev_watts"
|
||||
else
|
||||
run timeout 10 nvidia-smi -pl "$prev_watts"
|
||||
fi
|
||||
fi
|
||||
[[ "$DRY_RUN" == "1" ]] || rm -f "$STATE_DIR/gpu_power_limit_watts.prev"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 4. Re-assert lights-off rather than restoring anything: the preference is no
|
||||
# lighting at all, ever, so the morning must not turn the RGB back on.
|
||||
if [[ "$RGB_ENABLE" == "1" ]] && command -v openrgb >/dev/null 2>&1; then
|
||||
run env HOME="$RGB_HOME" openrgb --mode "$RGB_OFF_MODE" --color "$RGB_OFF_COLOR"
|
||||
fi
|
||||
|
||||
# 5. Record state BEFORE the (possibly long) alarm wait, so re-fired unlock
|
||||
# triggers dedupe on the state token instead of double-starting things.
|
||||
if [[ "$DRY_RUN" != "1" ]]; then
|
||||
echo UNLOCKED >"$STATE_FILE"
|
||||
fi
|
||||
|
||||
logg "night lockdown lifted — GUI restored, login surface unmasked"
|
||||
UNLOCK_EOF
|
||||
chmod 0755 "$UNLOCK_SCRIPT"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Morning-unlock systemd timer family (outside the shutdown fortress)
|
||||
# =============================================================================
|
||||
|
||||
install_unlock_units() {
|
||||
log_info "Installing morning-unlock timer family"
|
||||
cat >"$UNLOCK_SERVICE" <<EOF
|
||||
$MANAGED_BANNER
|
||||
[Unit]
|
||||
Description=Lift night lockdown (restore GUI, unmute, unmask login surface)
|
||||
DefaultDependencies=false
|
||||
After=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=$UNLOCK_SCRIPT
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
EOF
|
||||
|
||||
# Multiple staggered triggers + Persistent=true = dead-man robustness: a
|
||||
# single missed/failed 05:00 run cannot strand the machine, and each run is
|
||||
# idempotent so repeated firing is harmless.
|
||||
cat >"$UNLOCK_TIMER" <<EOF
|
||||
$MANAGED_BANNER
|
||||
[Unit]
|
||||
Description=Morning triggers to lift night lockdown
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 05:00:00
|
||||
OnCalendar=*-*-* 05:15:00
|
||||
OnCalendar=*-*-* 05:30:00
|
||||
OnCalendar=*-*-* 06:00:00
|
||||
OnCalendar=*-*-* 07:00:00
|
||||
Persistent=true
|
||||
AccuracySec=1s
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
}
|
||||
|
||||
# Lights stay off at ALL times, not just during lockdown. The board firmware
|
||||
# re-lights RAM/board/GPU on every power-on, so without this the RGB would be
|
||||
# back after each reboot and only go dark again at the next 21:00 lock.
|
||||
install_rgb_off_service() {
|
||||
log_info "Installing boot-time RGB-off service"
|
||||
cat >"$RGB_OFF_SERVICE" <<EOF
|
||||
$MANAGED_BANNER
|
||||
[Unit]
|
||||
Description=Turn all RGB lighting off (lights are meant to be off at all times)
|
||||
After=multi-user.target
|
||||
# The i2c DRAM/GPU controllers need their buses; the ASRock controller is USB.
|
||||
Wants=systemd-modules-load.service
|
||||
After=systemd-modules-load.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
# HOME pinned for the same reason as in the lock/unlock scripts: openrgb keeps
|
||||
# its state under HOME and systemd would otherwise differ from an interactive
|
||||
# sudo run. Detection takes ~2s before it applies. static+black rather than
|
||||
# "off": the ZOTAC GPU has no Off mode and the ASRock board ignores it.
|
||||
ExecStart=/usr/bin/env HOME=${RGB_HOME_DEFAULT} /usr/bin/openrgb --mode static --color 000000
|
||||
SuccessExitStatus=0 1
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
}
|
||||
|
||||
install_i2c_modules() {
|
||||
log_info "Installing i2c module-load for future RGB support"
|
||||
cat >"$I2C_MODULES_FILE" <<EOF
|
||||
@ -782,119 +100,10 @@ EOF
|
||||
# Install verification
|
||||
# =============================================================================
|
||||
|
||||
verify_install() {
|
||||
log_info "Verifying installation"
|
||||
local ok=true
|
||||
local path
|
||||
for path in "$ENTER_SCRIPT" "$UNLOCK_SCRIPT" "$CONF_FILE" \
|
||||
"$UNLOCK_SERVICE" "$UNLOCK_TIMER" "$RGB_OFF_SERVICE" "$I2C_MODULES_FILE"; do
|
||||
if [[ -e "$path" ]]; then
|
||||
log_ok "present: $path"
|
||||
else
|
||||
log_error "missing: $path"
|
||||
ok=false
|
||||
fi
|
||||
done
|
||||
if is_service_enabled night-lockdown-unlock.timer; then
|
||||
log_ok "night-lockdown-unlock.timer is enabled"
|
||||
else
|
||||
log_error "night-lockdown-unlock.timer is NOT enabled"
|
||||
ok=false
|
||||
fi
|
||||
# The action swap in the fortress check script is what actually invokes us.
|
||||
if grep -q "$ENTER_SCRIPT" /usr/local/bin/day-specific-shutdown-check.sh 2>/dev/null; then
|
||||
log_ok "day-specific-shutdown-check.sh calls the lockdown action"
|
||||
else
|
||||
log_warn "day-specific-shutdown-check.sh does NOT call $ENTER_SCRIPT yet"
|
||||
log_warn " → re-run setup_midnight_shutdown.sh to regenerate it (see header)"
|
||||
fi
|
||||
[[ "$ok" == true ]]
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Subcommands
|
||||
# =============================================================================
|
||||
|
||||
cmd_setup() {
|
||||
set_actual_user_vars
|
||||
print_setup_header "Night Lockdown"
|
||||
|
||||
ensure_dir "$STATE_DIR"
|
||||
[[ -f "$STATE_FILE" ]] || echo UNLOCKED >"$STATE_FILE"
|
||||
|
||||
write_config
|
||||
install_enter_script
|
||||
install_unlock_script
|
||||
install_unlock_units
|
||||
install_rgb_off_service
|
||||
install_i2c_modules
|
||||
|
||||
systemctl daemon-reload
|
||||
enable_service night-lockdown-unlock.timer
|
||||
enable_service rgb-off.service
|
||||
|
||||
echo ""
|
||||
if verify_install; then
|
||||
log_ok "Night lockdown installed."
|
||||
else
|
||||
log_warn "Night lockdown installed with warnings (see above)."
|
||||
fi
|
||||
echo ""
|
||||
log_info "Next: swap the shutdown action by re-running setup_midnight_shutdown.sh"
|
||||
log_info " (it must call $ENTER_SCRIPT instead of powering off)."
|
||||
log_info "Emergency unlock over SSH: sudo $0 unlock"
|
||||
}
|
||||
|
||||
cmd_status() {
|
||||
local state="unknown"
|
||||
[[ -r "$STATE_FILE" ]] && state="$(cat "$STATE_FILE")"
|
||||
echo "Night lockdown state : $state"
|
||||
echo "lightdm.service : $(systemctl is-active lightdm.service 2>/dev/null || true)"
|
||||
echo "getty@.service mask : $(systemctl is-enabled getty@.service 2>/dev/null || true)"
|
||||
echo "autovt@.service mask : $(systemctl is-enabled autovt@.service 2>/dev/null || true)"
|
||||
echo "unlock timer : $(systemctl is-active night-lockdown-unlock.timer 2>/dev/null || true) / $(systemctl is-enabled night-lockdown-unlock.timer 2>/dev/null || true)"
|
||||
echo ""
|
||||
echo "Next unlock triggers:"
|
||||
systemctl list-timers night-lockdown-unlock.timer --no-pager 2>/dev/null || true
|
||||
}
|
||||
|
||||
cmd_unlock() {
|
||||
log_info "Emergency unlock: restoring GUI now"
|
||||
DRY_RUN="" "$UNLOCK_SCRIPT"
|
||||
echo ""
|
||||
log_warn "The curfew is still armed: the next 30-min check tick will re-lock."
|
||||
log_warn "To stay unlocked until morning, register an override (friction by design):"
|
||||
if [[ -x "$OVERRIDE_MANAGER" ]]; then
|
||||
local now_h until_str
|
||||
now_h="$(date '+%Y-%m-%d %H:%M')"
|
||||
# Next 05:00 boundary (tomorrow if already past 05:00 today).
|
||||
if [[ "$(date +%H)" -lt 5 ]]; then
|
||||
until_str="$(date '+%Y-%m-%d') 05:00"
|
||||
else
|
||||
until_str="$(date -d tomorrow '+%Y-%m-%d') 05:00"
|
||||
fi
|
||||
echo " sudo $OVERRIDE_MANAGER add '$now_h' '$until_str' 'emergency unlock'"
|
||||
else
|
||||
log_warn " (override manager not found at $OVERRIDE_MANAGER)"
|
||||
fi
|
||||
}
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Night Lockdown — replace the midnight power-off with a GUI lockout that keeps
|
||||
background servers running.
|
||||
|
||||
Usage:
|
||||
sudo $0 setup Install/refresh the lock+unlock action and morning timer
|
||||
$0 status Show current lockdown state and timer status
|
||||
sudo $0 unlock Emergency: lift the lockdown right now (use over SSH)
|
||||
$0 help Show this help
|
||||
|
||||
After 'setup', re-run setup_midnight_shutdown.sh so the scheduled check calls
|
||||
$ENTER_SCRIPT instead of powering off.
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
local cmd="${1:-setup}"
|
||||
# Elevate BEFORE shifting so the subcommand survives the sudo re-exec.
|
||||
|
||||
@ -9,11 +9,23 @@ sec_tests_compulsive_block() {
|
||||
# ==================================================================
|
||||
echo "--- COMPULSIVE OPENING BLOCK ---"
|
||||
|
||||
compulsive_file="$REPO_DIR/scripts/periodic_background/digital_wellbeing/block_compulsive_opening.sh"
|
||||
compulsive_dir="$REPO_DIR/scripts/periodic_background/digital_wellbeing"
|
||||
compulsive_file="$compulsive_dir/block_compulsive_opening.sh"
|
||||
|
||||
# The blocker was split into lib/cco_*.sh under the 250-line cap, so these
|
||||
# two checks search the entry script AND its libs. Grepping the entry
|
||||
# script alone made them report "not found" for code that had simply moved
|
||||
# one file over — a false failure that says nothing about the feature.
|
||||
# Searching the set keeps the assertion about the FEATURE existing, which
|
||||
# is what it was always for, and survives the next split too.
|
||||
compulsive_sources=("$compulsive_file")
|
||||
for compulsive_lib in "$compulsive_dir"/lib/cco_*.sh; do
|
||||
[[ -f "$compulsive_lib" ]] && compulsive_sources+=("$compulsive_lib")
|
||||
done
|
||||
|
||||
# Test 17: Auto-close timer configuration exists
|
||||
if [[ -f "$compulsive_file" ]]; then
|
||||
if grep -q "AUTO_CLOSE_TIMEOUT_MINUTES" "$compulsive_file"; then
|
||||
if grep -qs "AUTO_CLOSE_TIMEOUT_MINUTES" "${compulsive_sources[@]}"; then
|
||||
test_result "Auto-close timer configuration exists" "pass"
|
||||
else
|
||||
test_result "Auto-close timer configuration exists" "fail" "Variable not found"
|
||||
@ -24,7 +36,7 @@ sec_tests_compulsive_block() {
|
||||
|
||||
# Test 18: launch_with_timer function exists
|
||||
if [[ -f "$compulsive_file" ]]; then
|
||||
if grep -q "launch_with_timer" "$compulsive_file"; then
|
||||
if grep -qs "launch_with_timer" "${compulsive_sources[@]}"; then
|
||||
test_result "launch_with_timer function exists" "pass"
|
||||
else
|
||||
test_result "launch_with_timer function exists" "fail" "Function not found"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user