Split three near-miss linux_configuration scripts

turn_off_auto_idle_screen_shutdown.sh 289 -> 180, mtk_root/install.sh
262 -> 141, setup_gitea.sh 255 -> 198. A deliberately small batch to
check jscpd before scaling; it stayed well under 2%.

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

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

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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
This commit is contained in:
Krzysztof Rudnicki 2026-08-16 18:38:43 +02:00
parent dadd33f82d
commit 658988ef9b
8 changed files with 398 additions and 297 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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