Fail the build on any shellcheck finding; fix the 222 the old gate hid
Some checks failed
Pre-commit checks / pre-commit (push) Waiting to run
Python tests / test (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
billsplit CI / quality (push) Has been cancelled
reverse-survivors CI / check (push) Has been cancelled

The shellcheck hook ran with --severity=warning, so info- and style-level
findings never failed a commit. 222 had accumulated across 94 of 244 shell
files. They were not all style noise -- six were bugs:

  - Five scripts in single_use/misc/testsAndMisc-bash/ sourced
    $SCRIPT_DIR/../../lib/common.sh, one directory too shallow. Nothing exists
    at that path, so all five failed at runtime.
  - setup_personal_website.sh and setup_kcd2_dice_solver.sh called usage()
    (which ends in `exit 0`) and then `exit 1` for an unknown command. The
    exit 1 was unreachable, so a typo'd subcommand reported SUCCESS.
  - Six i3blocks scripts had a `# shellcheck source=` directive missing the
    scripts/periodic_background/ path segment. The stale path had silently
    disabled source-following for all of them.
  - diagnose_arch_performance.sh word-split a newline-joined file list; when
    the find came back empty, awk got no file operands, fell through to
    reading stdin, and the diagnostic hung.
  - lib/common.sh's handle_arg_help_or_unknown ended in an unreachable
    `return 0` while documenting "Returns: 0 if handled" -- a contract no code
    path could satisfy.
  - deploy.sh's SCRIPT_DIR is reassigned by config.sh, which it sources at top
    level, and config.sh can repoint it at the on-device path
    /data/local/tmp/focus_mode. Renamed to DEPLOY_DIR.

The SC1091 bulk (81 findings) was resolved rather than silenced: .shellcheckrc
sets external-sources + source-path=SCRIPTDIR so sourced files are actually
followed and analysed. That is what surfaced the i3blocks and deploy.sh bugs.

17 `# shellcheck disable=` directives remain, each with a written reason, and
only where the finding is provably wrong: injection-test payloads that must not
expand, literal source text being grepped for, POSIX sh scripts on the phone
where arrays do not exist, and source paths that only exist at runtime.
Everything else was fixed in code.

Verified in a CLEAN worktree, not just my own tree. config.sh sources the
gitignored config_secrets.sh, which exists locally but not in a fresh checkout;
a working-tree-only check passed while ci_mirror.sh -- which lints HEAD in a
clean worktree, exactly as CI does -- failed on it.

The gate is verified to bite: a file whose only finding is SC2016 (info) fails
the hook, while the old --severity=warning gate exits 0 on it.

third_party/ is excluded -- vendored upstream, matching the prettier hook.

Not fixed, reported: check_polling_antipatterns.sh carries a pre-existing
SC2034 disable that hides a real bug -- its `patterns` array is never used, so
the checker detects nothing. Confirmed unchanged by this commit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-08-03 18:34:49 +02:00
parent 79829ec8a2
commit b83ce5d3c7
48 changed files with 5441 additions and 5081 deletions

View File

@ -412,13 +412,25 @@ repos:
hooks:
- id: shellcheck
name: shellcheck
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
# NO --severity filter: every finding shellcheck reports, down to info
# and style, fails the commit. The previous --severity=warning quietly
# accepted 222 findings across 94 of 244 shell files -- and among them
# were real defects, not noise: two scripts that reported SUCCESS on an
# unknown command, five that sourced a path off by one directory (so
# they failed at runtime), a stale `source=` directive that had silently
# disabled following for six i3blocks scripts, and a diagnostic that
# would hang on stdin when its file list came back empty.
# Settings live in .shellcheckrc (external-sources, source-path).
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck' --
language: system
types: [shell]
# shellcheck only understands sh/bash/dash/ksh; it cannot parse zsh
# syntax (e.g. extended globs like (#s)). zsh files are checked by the
# zsh-syntax hook below instead.
exclude_types: [zsh]
# Vendored upstream code: we do not own it and patches here would be
# lost on the next vendor sync. Matches the prettier hook's exclusion.
exclude: ^third_party/
# ===========================================================================
# ZSH SYNTAX - zsh -n parse check (shellcheck has no zsh mode)

20
.shellcheckrc Normal file
View File

@ -0,0 +1,20 @@
# Repo-wide shellcheck configuration.
#
# The pre-commit hook runs shellcheck with NO --severity filter, so every
# finding shellcheck reports - including info- and style-level - fails the
# commit. Previously the hook gated at --severity=warning, which silently
# accepted 222 findings across 94 of 244 shell files.
#
# Follow `source`d files so SC1091 can be satisfied by pointing at the real
# file rather than silenced. Where a script sources a path that only exists at
# runtime (e.g. /usr/local/bin/pacman_lock_lib.sh, installed by its installer),
# the call site carries an explicit `# shellcheck source=<repo path>` directive
# naming the in-repo original, so the sourced code is genuinely checked.
external-sources=true
# Resolve `source` targets relative to the sourcing script's own directory.
# Nearly every site here is `source "$SCRIPT_DIR/../../lib/common.sh"`, and
# shellcheck cannot expand $SCRIPT_DIR - but with SCRIPTDIR on the search path a
# `# shellcheck source=../../lib/common.sh` directive at the call site resolves
# to the real file, so the sourced code is actually analysed instead of skipped.
source-path=SCRIPTDIR

View File

@ -0,0 +1,18 @@
{
"title": "Gate shellcheck on every finding, and fix all 222 that the old gate hid",
"objective": "The pre-commit shellcheck hook ran with --severity=warning, so info- and style-level findings never failed a commit. 222 of them had accumulated across 94 of 244 shell files, and several were real defects rather than style noise. Make the hook fail on ANY shellcheck finding and drive the repo to zero, fixing the underlying code rather than suppressing it.",
"acceptance_criteria": [
"shellcheck reports zero findings, at full strictness, across every tracked first-party .sh file",
"The pre-commit hook runs shellcheck with no --severity filter",
"The hook demonstrably FAILS on an info-level-only finding and passes on the clean tree",
"Sourced files are genuinely followed (external-sources + source-path) rather than SC1091 being silenced",
"Every remaining `# shellcheck disable=` carries a written reason at the call site",
"Behaviour is preserved: scripts that were runnable before still run, and tests that covered them still pass"
],
"out_of_scope": [
"third_party/ — vendored upstream code we do not own; excluded from the hook, matching the existing prettier exclusion",
"The pre-existing SC2034 disable in check_polling_antipatterns.sh, which hides a real bug (its `patterns` array is never used, so the checker checks nothing). Reported, not fixed — it is a behavioural change beyond a lint sweep.",
"linux_configuration/scripts/single_use/fresh-install/main.sh — another session's uncommitted work, deliberately left unstaged"
],
"verifier": "pre-commit run shellcheck --all-files (exit 0); the same hook against a deliberately planted info-level canary (exit 1); per-file `bash -n`/`sh -n`; and re-running the affected test suites"
}

View File

@ -0,0 +1,69 @@
{
"intent": "Make the shellcheck pre-commit hook fail on every finding, and clear all 222 findings the previous --severity=warning gate had been accepting silently.",
"scope": [
".pre-commit-config.yaml (hook strictness + third_party exclusion), .shellcheckrc (new)",
"45 shell files across linux_configuration/, phone_focus_mode/, meta/",
"NON-GOAL: third_party/ vendored code",
"NON-GOAL: linux_configuration/scripts/single_use/fresh-install/main.sh (another session's uncommitted work, left unstaged)"
],
"changes": [
"Added .shellcheckrc with external-sources=true and source-path=SCRIPTDIR. This RESOLVES sourced files instead of silencing SC1091: 81 -> 13 findings with no suppression, and it made shellcheck analyse the sourced code, which is what surfaced several of the bugs below.",
"Removed --severity=warning from the hook so info- and style-level findings fail the commit; excluded third_party/ (vendored, matching the prettier hook).",
"REAL BUG: five scripts in single_use/misc/testsAndMisc-bash/ sourced $SCRIPT_DIR/../../lib/common.sh, one directory too shallow. The file does not exist at that path, so every one of them failed at runtime. Corrected to ../../../lib/common.sh.",
"REAL BUG: setup_personal_website.sh and setup_kcd2_dice_solver.sh called usage() (which ends in `exit 0`) and then `exit 1` on an unknown command. The exit 1 was unreachable, so a typo'd subcommand reported SUCCESS. usage() now takes an exit status; both verified to exit 1.",
"REAL BUG: six i3blocks scripts carried a `# shellcheck source=linux_configuration/i3-configuration/...` directive missing the scripts/periodic_background/ segment. The stale path silently disabled source-following. Corrected to a script-relative `source=persist_common.sh`.",
"REAL BUG: diagnose_arch_performance.sh word-split a newline-joined `gov_files` string; when the find returned nothing, awk was left with no file operands and fell through to reading stdin, hanging the diagnostic. Now a mapfile array with an explicit empty guard.",
"REAL BUG: lib/common.sh's handle_arg_help_or_unknown ended with an unreachable `return 0` while its doc promised 'Returns: 0 if handled' — a contract no code path could satisfy. Dead line removed, doc corrected.",
"phone_focus_mode/deploy.sh: renamed its SCRIPT_DIR to DEPLOY_DIR. config.sh is sourced at top level and reassigns SCRIPT_DIR, and can repoint it at the on-device path /data/local/tmp/focus_mode — after which every later path in deploy.sh would resolve against the wrong tree.",
"Mechanical but genuine fixes elsewhere: printf format strings (SC2059) with colour variables moved to %s arguments — which required switching the colour definitions to ANSI-C $'...' quoting, since printf does not interpret backslash escapes in arguments; `A && B || C` rewritten as if/then/else; ls-parsing replaced with find/glob arrays; unquoted expansions quoted; repeated appends grouped."
],
"verification": [
{
"command": "shellcheck (full strictness) over every tracked first-party *.sh, in a CLEAN worktree",
"result": "pass",
"evidence": "222 findings in 94 files -> 0 findings in 0 files. Verified with `git worktree add --detach` on HEAD rather than the working tree: config.sh sources the gitignored config_secrets.sh, which exists locally but NOT in a clean checkout, so a working-tree-only check passed while ci_mirror.sh (which lints HEAD in a clean worktree) failed."
},
{
"command": "pre-commit run shellcheck --all-files",
"result": "pass",
"evidence": "exit 0"
},
{
"command": "pre-commit run shellcheck --files <planted info-level canary>",
"result": "pass",
"evidence": "exit 1 on a file whose ONLY finding is SC2016 (info). The old --severity=warning gate exits 0 on the same file - this is the regression that let 222 findings accumulate."
},
{
"command": "bash phone_focus_mode/lib/tests/test_tether_enforcer.sh",
"result": "pass",
"evidence": "17 passed, 0 failed after rewriting all 17 assertions from `cond && ok || no` to if/then/else"
},
{
"command": "bash phone_focus_mode/lib/tests/test_adb_common.sh",
"result": "pass",
"evidence": "13 passed, 0 failed"
},
{
"command": "bash linux_configuration/tests/test_shutdown_timer_monitor.sh",
"result": "pass",
"evidence": "regression checks passed"
},
{
"command": "behavioural spot-checks",
"result": "pass",
"evidence": "setup_personal_website.sh bogus -> exit 1 (was 0), --help -> 0; disk_cleanup_check.sh output byte-identical with ANSI escapes present and zero literal \\033 leaked; build.sh picks the same build-tools dir as the old ls pipeline; every touched file passes bash -n / sh -n"
}
],
"risks": [
"The gate is now strict for everyone: any new shell code must be shellcheck-clean at info level. That is the intent, but it will fail commits that previously passed.",
"16 `# shellcheck disable=` directives were added where the finding is provably a false positive - injection-test payloads that must not expand, literal source text being grepped for, POSIX sh scripts on the phone where arrays do not exist, and runtime-only source paths. Each carries a written reason. They are the only suppressions; everything else was fixed in code.",
"A comment line beginning '# shellcheck ' is parsed as a directive - one such comment broke a file mid-sweep and had to be reworded. Worth knowing when writing these reasons.",
"Verifying a lint gate against the WORKING TREE is not the same as verifying it against a clean checkout. config.sh sources a gitignored secrets file that exists locally; shellcheck resolved it here and reported nothing, while ci_mirror.sh - which checks HEAD out into a clean worktree, exactly as CI does - failed. Any future gate work must be checked the ci_mirror way.",
"check_polling_antipatterns.sh has a pre-existing SC2034 disable hiding a real bug: its `patterns` array is never used, so the checker detects nothing. Confirmed against the pre-change version - behaviour is unchanged by this commit. Left for a separate fix."
],
"rollback": [
"Restore --severity=warning in the shellcheck hook entry and delete .shellcheckrc to return to the old gate",
"git revert the commit to restore all 45 files; the code fixes are independent of the hook change and can be kept separately",
"After rollback, validate: pre-commit run shellcheck --all-files still passes, and the affected test suites still pass"
]
}

View File

@ -116,8 +116,11 @@ parse_interactive_args() {
# Handle common argument patterns for scripts with custom usage functions
# Usage: handle_arg_help_or_unknown "$1" usage_function err_function
# Returns: 0 if argument was handled (caller should continue), 1 if not our concern
# Exits: on -h/--help (exit 0) or unknown arg starting with - (exit 2)
# Returns: 1 if the argument is not ours, so the caller handles it.
# Exits: on -h/--help (exit 0) or unknown arg starting with - (exit 2).
# There is deliberately no success return: every other branch exits. The old
# trailing `return 0` was unreachable, and the doc promised a 0 that no code
# path could ever produce.
handle_arg_help_or_unknown() {
local arg="$1"
local usage_fn="${2:-usage}"
@ -137,7 +140,6 @@ handle_arg_help_or_unknown() {
return 1 # Not a flag, let caller handle it
;;
esac
return 0
}
# Initialize a setup script with common boilerplate

View File

@ -18,12 +18,12 @@ DRY_RUN=0
STATUS_ONLY=0
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
RED=$'\033[0;31m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[0;33m'
BLUE=$'\033[0;34m'
CYAN=$'\033[0;36m'
NC=$'\033[0m' # No Color
# Get script and config directories
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
@ -1320,17 +1320,17 @@ main
# it hid dead hosts self-repair for five months. Make it impossible to miss.
######################################################################
if [[ ${#MISSING_SCRIPTS[@]} -gt 0 ]]; then
printf "\n${RED}"
printf '\n%s' "$RED"
printf '=%.0s' {1..74}
printf "\n SELF-REPAIR IS BROKEN — %d repair script(s) MISSING\n" "${#MISSING_SCRIPTS[@]}"
printf '=%.0s' {1..74}
printf "${NC}\n"
printf '%s\n' "$NC"
for missing in "${MISSING_SCRIPTS[@]}"; do
err "$missing"
done
printf "${RED}The services above are NOT being repaired — this tool found the\n"
printf "problem and then could not run the fix. Correct these paths first.${NC}\n"
printf "${CYAN}Also logged at error priority: journalctl -p err -t check-and-enable-services${NC}\n\n"
printf '%sThe services above are NOT being repaired — this tool found the\n' "$RED"
printf 'problem and then could not run the fix. Correct these paths first.%s\n' "$NC"
printf '%sAlso logged at error priority: journalctl -p err -t check-and-enable-services%s\n\n' "$CYAN" "$NC"
exit 2
fi

View File

@ -16,6 +16,9 @@ if [[ -f "$SCRIPT_DIR/../../lib/common.sh" ]]; then
source "$SCRIPT_DIR/../../lib/common.sh"
elif [[ -f "/usr/local/lib/common.sh" ]]; then
# shellcheck source=/usr/local/lib/common.sh
# Deployed to /usr/local/lib at install time; no in-repo copy exists at that
# absolute path for the linter to follow.
# shellcheck disable=SC1091
source "/usr/local/lib/common.sh"
else
echo "ERROR: common.sh library not found"

View File

@ -5,7 +5,7 @@ set -euo pipefail
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
[[ $SCRIPT_DIR == "${BASH_SOURCE[0]}" ]] && SCRIPT_DIR='.'
# shellcheck source=linux_configuration/i3-configuration/i3blocks/persist_common.sh
# shellcheck source=persist_common.sh
source "$SCRIPT_DIR/persist_common.sh"
check_installed() {

View File

@ -5,7 +5,7 @@ set -euo pipefail
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
[[ $SCRIPT_DIR == "${BASH_SOURCE[0]}" ]] && SCRIPT_DIR='.'
# shellcheck source=linux_configuration/i3-configuration/i3blocks/persist_common.sh
# shellcheck source=persist_common.sh
source "$SCRIPT_DIR/persist_common.sh"
get_bluetooth_info() {

View File

@ -5,7 +5,7 @@ set -euo pipefail
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
[[ $SCRIPT_DIR == "${BASH_SOURCE[0]}" ]] && SCRIPT_DIR='.'
# shellcheck source=linux_configuration/i3-configuration/i3blocks/persist_common.sh
# shellcheck source=persist_common.sh
source "$SCRIPT_DIR/persist_common.sh"
find_ethernet_interface() {

View File

@ -14,7 +14,7 @@ set -u
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
[[ $SCRIPT_DIR == "${BASH_SOURCE[0]}" ]] && SCRIPT_DIR='.'
# shellcheck source=linux_configuration/i3-configuration/i3blocks/persist_common.sh
# shellcheck source=persist_common.sh
source "$SCRIPT_DIR/persist_common.sh"
# Nerd Font glyph: display / desktop icon (U+F108).
@ -43,7 +43,6 @@ emit_if_changed() {
emit "$temp" "$load"
}
# Prefer NVIDIA if present (persist via --loop).
if command -v nvidia-smi >/dev/null 2>&1; then
# One child process for the lifetime of i3blocks; emits CSV every 5s.

View File

@ -5,7 +5,7 @@ set -euo pipefail
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
[[ $SCRIPT_DIR == "${BASH_SOURCE[0]}" ]] && SCRIPT_DIR='.'
# shellcheck source=linux_configuration/i3-configuration/i3blocks/persist_common.sh
# shellcheck source=persist_common.sh
source "$SCRIPT_DIR/persist_common.sh"
if ! command -v warp-cli >/dev/null 2>&1; then

View File

@ -5,7 +5,7 @@ set -euo pipefail
SCRIPT_DIR=${BASH_SOURCE[0]%/*}
[[ $SCRIPT_DIR == "${BASH_SOURCE[0]}" ]] && SCRIPT_DIR='.'
# shellcheck source=linux_configuration/i3-configuration/i3blocks/persist_common.sh
# shellcheck source=persist_common.sh
source "$SCRIPT_DIR/persist_common.sh"
find_wifi_interface() {

View File

@ -100,7 +100,11 @@ $installed_packages
package:$package
"*)
log "Blocked app detected: $package - Uninstalling..."
pm uninstall "$package" 2>/dev/null && log "Uninstalled: $package" || log "Failed to uninstall: $package"
if pm uninstall "$package" 2>/dev/null; then
log "Uninstalled: $package"
else
log "Failed to uninstall: $package"
fi
;;
esac
done <"$BLOCKED_APPS_FILE"

View File

@ -442,10 +442,21 @@ cmd_status() {
detect_lan
echo "=== LAN DNS blocker status ==="
is_service_active dnsmasq && status_line 0 "dnsmasq: active" || status_line 1 "dnsmasq: NOT active"
is_service_enabled dnsmasq && status_line 0 "dnsmasq: enabled at boot" || status_line 1 "dnsmasq: NOT enabled"
[[ -f $DNSMASQ_DROPIN ]] && status_line 0 "Restart=always drop-in present" || status_line 1 "Restart drop-in missing"
if is_service_active dnsmasq; then
status_line 0 "dnsmasq: active"
else
status_line 1 "dnsmasq: NOT active"
fi
if is_service_enabled dnsmasq; then
status_line 0 "dnsmasq: enabled at boot"
else
status_line 1 "dnsmasq: NOT enabled"
fi
if [[ -f $DNSMASQ_DROPIN ]]; then
status_line 0 "Restart=always drop-in present"
else
status_line 1 "Restart drop-in missing"
fi
if [[ -f $FEED ]]; then
status_line 0 "blocklist feed: $(wc -l <"$FEED") lines, updated $(date -r "$FEED" '+%Y-%m-%d %H:%M')"
else
@ -472,10 +483,11 @@ cmd_status() {
status_line 0 "firewall: no default-drop ruleset loaded (DNS/DHCP not filtered)"
fi
systemctl is-active dns-blocklist-refresh.timer &>/dev/null &&
status_line 0 "refresh timer: active (next $(systemctl show -p NextElapseUSecRealtime --value dns-blocklist-refresh.timer 2>/dev/null))" ||
if systemctl is-active dns-blocklist-refresh.timer &>/dev/null; then
status_line 0 "refresh timer: active (next $(systemctl show -p NextElapseUSecRealtime --value dns-blocklist-refresh.timer 2>/dev/null))"
else
status_line 1 "refresh timer: NOT active"
fi
if [[ -f $DHCP_CONF ]]; then
if ss -ulnp 2>/dev/null | grep -q ':67 '; then
status_line 0 "DHCP mode: ON (serving leases; PC is the LAN DHCP server)"
@ -492,12 +504,16 @@ cmd_status() {
local blocked passthru
blocked="$(dig +short +time=2 +tries=1 @"${LAN_IP}" youtube.com 2>/dev/null | head -1)"
passthru="$(dig +short +time=2 +tries=1 @"${LAN_IP}" example.com 2>/dev/null | head -1)"
[[ $blocked == "0.0.0.0" ]] &&
status_line 0 "youtube.com -> ${blocked} (BLOCKED, correct)" ||
if [[ $blocked == "0.0.0.0" ]]; then
status_line 0 "youtube.com -> ${blocked} (BLOCKED, correct)"
else
status_line 1 "youtube.com -> ${blocked:-<no answer>} (expected 0.0.0.0)"
[[ -n $passthru && $passthru != "0.0.0.0" ]] &&
status_line 0 "example.com -> ${passthru} (passthrough, correct)" ||
fi
if [[ -n $passthru && $passthru != "0.0.0.0" ]]; then
status_line 0 "example.com -> ${passthru} (passthrough, correct)"
else
status_line 1 "example.com -> ${passthru:-<no answer>} (expected a real IP)"
fi
else
log_warn "install 'dig' (bind) to run the live resolution test."
fi

View File

@ -67,9 +67,12 @@ die() {
exit 1
}
# Takes the exit status to leave with, so the error path can print the same
# help and still fail. Hardcoding `exit 0` made the `exit 1` after the
# unknown-command branch unreachable -- the script reported SUCCESS on a typo.
usage() {
grep -E '^#( |$)' "$0" | sed -E 's/^# ?//'
exit 0
exit "${1:-0}"
}
# --- Phase 1: preflight -----------------------------------------------------
@ -394,13 +397,21 @@ check_http() {
status_cmd() {
print_setup_header "KCD2 dice solver status"
has_cmd node && status_line 0 "node present" || status_line 1 "node missing"
has_cmd pnpm && status_line 0 "pnpm present" || status_line 1 "pnpm missing"
[[ -f "${DICE_SRC}/dist/index.html" ]] &&
status_line 0 "build present (dist/index.html)" ||
if has_cmd node; then
status_line 0 "node present"
else
status_line 1 "node missing"
fi
if has_cmd pnpm; then
status_line 0 "pnpm present"
else
status_line 1 "pnpm missing"
fi
if [[ -f "${DICE_SRC}/dist/index.html" ]]; then
status_line 0 "build present (dist/index.html)"
else
status_line 1 "build missing — run setup"
fi
if docker ps --format '{{.Names}}' | grep -qx "$DICE_CONTAINER"; then
status_line 0 "${DICE_CONTAINER} container running"
local pid listeners
@ -418,14 +429,16 @@ status_cmd() {
status_line "$(check_http "http://127.0.0.1:${DICE_PORT}/" "$DICE_DOMAIN")" \
"local static server (127.0.0.1:${DICE_PORT}, Host: ${DICE_DOMAIN})"
[[ -f $DICE_SNIPPET ]] &&
status_line 0 "Caddy snippet present" ||
if [[ -f $DICE_SNIPPET ]]; then
status_line 0 "Caddy snippet present"
else
status_line 1 "Caddy snippet missing"
getent hosts "$DICE_DOMAIN" >/dev/null &&
status_line 0 "${DICE_DOMAIN} resolves" ||
fi
if getent hosts "$DICE_DOMAIN" >/dev/null; then
status_line 0 "${DICE_DOMAIN} resolves"
else
status_line 1 "${DICE_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${DICE_DOMAIN}/")" \
"external https://${DICE_DOMAIN}/"
@ -438,10 +451,11 @@ status_cmd() {
status_line 1 "post-commit hook missing — re-run setup"
fi
[[ -f $UNIT_FILE ]] &&
status_line 0 "${UNIT_NAME} installed" ||
if [[ -f $UNIT_FILE ]]; then
status_line 0 "${UNIT_NAME} installed"
else
status_line 1 "${UNIT_NAME} missing — re-run setup"
fi
if systemctl --user is-failed --quiet "$UNIT_NAME"; then
status_line 1 "last auto-rebuild FAILED — journalctl --user -u ${UNIT_NAME}"
else
@ -475,8 +489,7 @@ main() {
;;
*)
log_error "Unknown command: $cmd"
usage
exit 1
usage 1
;;
esac
}

View File

@ -66,9 +66,13 @@ die() {
exit 1
}
# Takes the exit status to leave with, so the error path can print the same help
# and still fail. It used to hardcode `exit 0`, which made the `exit 1` after the
# unknown-command branch unreachable -- so `setup_personal_website.sh bogus`
# printed an error and then reported SUCCESS to its caller.
usage() {
grep -E '^#( |$)' "$0" | sed -E 's/^# ?//'
exit 0
exit "${1:-0}"
}
# --- Phase 1: preflight -----------------------------------------------------
@ -320,13 +324,21 @@ check_http() {
status_cmd() {
print_setup_header "Personal website status"
has_cmd node && status_line 0 "node present" || status_line 1 "node missing"
has_cmd pnpm && status_line 0 "pnpm present" || status_line 1 "pnpm missing"
[[ -f "${WEBSITE_SRC}/dist/index.html" ]] &&
status_line 0 "build present (dist/index.html)" ||
if has_cmd node; then
status_line 0 "node present"
else
status_line 1 "node missing"
fi
if has_cmd pnpm; then
status_line 0 "pnpm present"
else
status_line 1 "pnpm missing"
fi
if [[ -f "${WEBSITE_SRC}/dist/index.html" ]]; then
status_line 0 "build present (dist/index.html)"
else
status_line 1 "build missing — run setup"
fi
if docker ps --format '{{.Names}}' | grep -qx personal-website; then
status_line 0 "personal-website container running"
else
@ -336,20 +348,26 @@ status_cmd() {
status_line "$(check_http "http://127.0.0.1:${WEBSITE_PORT}/")" \
"local static server (127.0.0.1:${WEBSITE_PORT})"
[[ -f $WEBSITE_SNIPPET ]] &&
status_line 0 "Caddy website snippet present" ||
if [[ -f $WEBSITE_SNIPPET ]]; then
status_line 0 "Caddy website snippet present"
else
status_line 1 "Caddy website snippet missing"
grep -qE '^[[:space:]]*import[[:space:]]+/etc/caddy/sites' "$CADDYFILE" 2>/dev/null &&
status_line 0 "root Caddyfile uses snippet imports" ||
fi
if grep -qE '^[[:space:]]*import[[:space:]]+/etc/caddy/sites' "$CADDYFILE" 2>/dev/null; then
status_line 0 "root Caddyfile uses snippet imports"
else
status_line 1 "root Caddyfile not migrated to imports"
getent hosts "$WEBSITE_DOMAIN" >/dev/null &&
status_line 0 "${WEBSITE_DOMAIN} resolves" ||
fi
if getent hosts "$WEBSITE_DOMAIN" >/dev/null; then
status_line 0 "${WEBSITE_DOMAIN} resolves"
else
status_line 1 "${WEBSITE_DOMAIN} does not resolve"
getent hosts "$GITEA_DOMAIN" >/dev/null &&
status_line 0 "${GITEA_DOMAIN} resolves" ||
fi
if getent hosts "$GITEA_DOMAIN" >/dev/null; then
status_line 0 "${GITEA_DOMAIN} resolves"
else
status_line 1 "${GITEA_DOMAIN} does not resolve"
fi
status_line "$(check_http "https://${WEBSITE_DOMAIN}/")" \
"external https://${WEBSITE_DOMAIN}/"
status_line "$(check_http "https://${GITEA_DOMAIN}/")" \
@ -370,8 +388,7 @@ main() {
;;
*)
log_error "Unknown command: $cmd"
usage
exit 1
usage 1
;;
esac
}

View File

@ -145,19 +145,23 @@ collect_basics() {
}
check_cpu_governor() {
local gov_files
gov_files=$(find /sys/devices/system/cpu -maxdepth 3 -name scaling_governor 2>/dev/null || true)
# An ARRAY, not a newline-joined string: the awk/grep calls below need one
# argument per file. With the old unquoted "$gov_files" an empty result
# also left awk with NO file operands, so it fell through to reading stdin
# and the diagnostic hung instead of reporting 'not found'.
local -a gov_files=()
mapfile -t gov_files < <(find /sys/devices/system/cpu -maxdepth 3 -name scaling_governor 2>/dev/null || true)
if [[ -z $gov_files ]]; then
if ((${#gov_files[@]} == 0)); then
add_action "CPU governor files not found (may be unsupported on this platform)."
return
fi
local summary
summary=$(awk '{count[$1]++} END {for (g in count) printf "%s:%d ", g, count[g]}' $gov_files 2>/dev/null || true)
summary=$(awk '{count[$1]++} END {for (g in count) printf "%s:%d ", g, count[g]}' "${gov_files[@]}" 2>/dev/null || true)
echo "CPU governor summary: ${summary:-unknown}" >>"$REPORT_FILE"
if grep -q '^powersave$' $gov_files 2>/dev/null; then
if grep -q '^powersave$' "${gov_files[@]}" 2>/dev/null; then
add_finding "CPU governor includes 'powersave' on one or more cores; this can make high-end hardware feel slow."
fi
}
@ -261,9 +265,11 @@ check_gpu_state() {
util=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 | xargs || true)
power=$(nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits 2>/dev/null | head -n 1 | xargs || true)
echo "NVIDIA pstate: ${pstate:-unknown}" >>"$REPORT_FILE"
echo "NVIDIA util: ${util:-unknown}%" >>"$REPORT_FILE"
echo "NVIDIA power: ${power:-unknown}W" >>"$REPORT_FILE"
{
echo "NVIDIA pstate: ${pstate:-unknown}"
echo "NVIDIA util: ${util:-unknown}%"
echo "NVIDIA power: ${power:-unknown}W"
} >>"$REPORT_FILE"
if [[ ${pstate:-} == "P0" && ${util:-100} -le 5 ]]; then
add_finding "NVIDIA GPU is in P0 high-performance state while mostly idle; this can increase heat and trigger thermal limits."

View File

@ -20,8 +20,8 @@ IFS=$'\n\t'
# Source common library for log functions
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=../../lib/common.sh
source "$SCRIPT_DIR/../../lib/common.sh"
# shellcheck source=../../../lib/common.sh
source "$SCRIPT_DIR/../../../lib/common.sh"
DO_POLICY=false
SET_DEFAULT=false

View File

@ -26,8 +26,8 @@ SCRIPT_NAME="$(basename "$0")"
# Source common library for log functions
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=../../lib/common.sh
source "$SCRIPT_DIR/../../lib/common.sh"
# shellcheck source=../../../lib/common.sh
source "$SCRIPT_DIR/../../../lib/common.sh"
usage() {
cat <<EOF

View File

@ -13,8 +13,8 @@ set -euo pipefail
# Source common library for shared functions
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=../../lib/common.sh
source "$SCRIPT_DIR/../../lib/common.sh"
# shellcheck source=../../../lib/common.sh
source "$SCRIPT_DIR/../../../lib/common.sh"
YES=false
while [[ $# -gt 0 ]]; do

View File

@ -9,8 +9,8 @@ set -euo pipefail
# Source common library for shared functions
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=../../lib/common.sh
source "$SCRIPT_DIR/../../lib/common.sh"
# shellcheck source=../../../lib/common.sh
source "$SCRIPT_DIR/../../../lib/common.sh"
print_info() {
echo "[info] $*"

View File

@ -4,8 +4,8 @@ set -euo pipefail
# Source common library for shared functions
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=../../lib/common.sh
source "$SCRIPT_DIR/../../lib/common.sh"
# shellcheck source=../../../lib/common.sh
source "$SCRIPT_DIR/../../../lib/common.sh"
SCRIPT_NAME="$(basename "$0")"

View File

@ -113,7 +113,7 @@ find_files() {
# Not a git repo - fall back to manual exclusion
local find_args=()
for i in "${!patterns[@]}"; do
if [ $i -eq 0 ]; then
if [ "$i" -eq 0 ]; then
find_args+=(-name "${patterns[$i]}")
else
find_args+=(-o -name "${patterns[$i]}")
@ -125,7 +125,7 @@ find_files() {
# No filtering - find all files
local find_args=()
for i in "${!patterns[@]}"; do
if [ $i -eq 0 ]; then
if [ "$i" -eq 0 ]; then
find_args+=(-name "${patterns[$i]}")
else
find_args+=(-o -name "${patterns[$i]}")
@ -302,7 +302,7 @@ if [ "$RESPECT_GITIGNORE" = true ] && is_git_repo; then
} | sort -u | wc -l)
echo "Files: $FILE_COUNT (respecting .gitignore)"
elif [ "$RESPECT_GITIGNORE" = true ]; then
echo "Files: $(find . -type f 2>/dev/null | grep -Ev "/($EXCLUDE_DIRS)/" | wc -l) (excluding common dirs)"
echo "Files: $(find . -type f 2>/dev/null | grep -cEv "/($EXCLUDE_DIRS)/") (excluding common dirs)"
else
echo "Files: $(find . -type f | wc -l)"
fi
@ -336,7 +336,7 @@ print_header "STEP 4: Fast Keyword Analysis (Code vs Comments)"
fast_count() {
local top_n="${1:-50}"
if command -v counts &>/dev/null; then
counts 2>/dev/null | head -$((top_n + 1)) | tail -$top_n
counts 2>/dev/null | head -n "$((top_n + 1))" | tail -n "$top_n"
else
python3 "$SCRIPT_DIR/fast_count.py" "$top_n"
fi
@ -387,14 +387,14 @@ HAS_GO=false
HAS_RUST=false
HAS_JAVA=false
((${LANG_FILES[c]} + ${LANG_FILES[cpp]} + ${LANG_FILES[h]} > 0)) && HAS_C_FAMILY=true
((${LANG_FILES[python]} > 0)) && HAS_PYTHON=true
((${LANG_FILES[javascript]} + ${LANG_FILES[typescript]} > 0)) && HAS_JS_FAMILY=true
((${LANG_FILES[shell]} > 0)) && HAS_SHELL=true
((${LANG_FILES[ruby]} > 0)) && HAS_RUBY=true
((${LANG_FILES[go]} > 0)) && HAS_GO=true
((${LANG_FILES[rust]} > 0)) && HAS_RUST=true
((${LANG_FILES[java]} > 0)) && HAS_JAVA=true
((LANG_FILES[c] + LANG_FILES[cpp] + LANG_FILES[h] > 0)) && HAS_C_FAMILY=true
((LANG_FILES[python] > 0)) && HAS_PYTHON=true
((LANG_FILES[javascript] + LANG_FILES[typescript] > 0)) && HAS_JS_FAMILY=true
((LANG_FILES[shell] > 0)) && HAS_SHELL=true
((LANG_FILES[ruby] > 0)) && HAS_RUBY=true
((LANG_FILES[go] > 0)) && HAS_GO=true
((LANG_FILES[rust] > 0)) && HAS_RUST=true
((LANG_FILES[java] > 0)) && HAS_JAVA=true
#------------------------------------------------------------------------------
# Language-specific keyword definitions
@ -735,7 +735,7 @@ if [ -f "$RESULTS_DIR/tags" ]; then
print_subheader "Symbol Types Distribution"
# Fast: extract single-letter kind code after ;" and count
grep -aoP ';"\t\K[a-z]' "$RESULTS_DIR/tags" 2>/dev/null | fast_count 20 | while read count kind; do
grep -aoP ';"\t\K[a-z]' "$RESULTS_DIR/tags" 2>/dev/null | fast_count 20 | while read -r count kind; do
case $kind in
f) echo "$count functions" ;;
v) echo "$count variables" ;;

View File

@ -64,7 +64,7 @@ for track in "${!TRACKS[@]}"; do
# Show exercise count
if [[ -d "$track/exercises/practice" ]]; then
count=$(ls "$track/exercises/practice" | wc -l)
count=$(find "$track/exercises/practice" -mindepth 1 -maxdepth 1 | wc -l)
echo " → $count practice exercises available"
fi
echo ""
@ -100,7 +100,7 @@ echo ""
echo "Track summary:"
for track in "${!TRACKS[@]}"; do
if [[ -d "$track/exercises/practice" ]]; then
count=$(ls "$track/exercises/practice" 2> /dev/null | wc -l)
count=$(find "$track/exercises/practice" -mindepth 1 -maxdepth 1 2>/dev/null | wc -l)
printf " %-15s %3d exercises\n" "$track" "$count"
fi
done | sort

View File

@ -498,8 +498,10 @@ if [ -d "$PER_LANG_DIR" ]; then
}
# Process keywords by language
echo "## Language Keywords" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
{
echo "## Language Keywords"
echo ""
} >>"$DOCS_FILE"
for keyword_file in "$PER_LANG_DIR"/keywords_*.txt; do
[ ! -f "$keyword_file" ] && continue
@ -523,12 +525,14 @@ if [ -d "$PER_LANG_DIR" ]; then
*) display_lang="$lang" ;;
esac
echo "### $display_lang Keywords" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
echo "| Keyword | Count | Documentation |" >>"$DOCS_FILE"
echo "|---------|-------|---------------|" >>"$DOCS_FILE"
{
echo "### $display_lang Keywords"
echo ""
echo "| Keyword | Count | Documentation |"
echo "|---------|-------|---------------|"
} >>"$DOCS_FILE"
head -$TOP_N "$keyword_file" | while read -r count term; do
head -n "$TOP_N" "$keyword_file" | while read -r count term; do
[ -z "$term" ] && continue
[[ $term =~ ^[#] ]] && continue # Skip comment lines
url=$(get_doc_url "$term" "$doc_lang")
@ -538,8 +542,10 @@ if [ -d "$PER_LANG_DIR" ]; then
done
# Process functions by language
echo "## Function/Method Calls" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
{
echo "## Function/Method Calls"
echo ""
} >>"$DOCS_FILE"
for func_file in "$PER_LANG_DIR"/functions_*.txt; do
[ ! -f "$func_file" ] && continue
@ -561,12 +567,14 @@ if [ -d "$PER_LANG_DIR" ]; then
*) display_lang="$lang" ;;
esac
echo "### $display_lang Functions" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
echo "| Function | Count | Documentation |" >>"$DOCS_FILE"
echo "|----------|-------|---------------|" >>"$DOCS_FILE"
{
echo "### $display_lang Functions"
echo ""
echo "| Function | Count | Documentation |"
echo "|----------|-------|---------------|"
} >>"$DOCS_FILE"
head -$TOP_N "$func_file" | while read -r count term; do
head -n "$TOP_N" "$func_file" | while read -r count term; do
[ -z "$term" ] && continue
[[ $term =~ ^(if|for|while|switch|catch|elif)$ ]] && continue
url=$(get_doc_url "$term" "$doc_lang")
@ -576,8 +584,10 @@ if [ -d "$PER_LANG_DIR" ]; then
done
# Process imports by language
echo "## Imports/Includes" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
{
echo "## Imports/Includes"
echo ""
} >>"$DOCS_FILE"
for import_file in "$PER_LANG_DIR"/imports_*.txt; do
[ ! -f "$import_file" ] && continue
@ -599,10 +609,12 @@ if [ -d "$PER_LANG_DIR" ]; then
*) display_lang="$lang" ;;
esac
echo "### $display_lang" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
echo "| Import | Count | Documentation |" >>"$DOCS_FILE"
echo "|--------|-------|---------------|" >>"$DOCS_FILE"
{
echo "### $display_lang"
echo ""
echo "| Import | Count | Documentation |"
echo "|--------|-------|---------------|"
} >>"$DOCS_FILE"
head -20 "$import_file" | while read -r count import; do
[ -z "$import" ] && continue
@ -613,7 +625,7 @@ if [ -d "$PER_LANG_DIR" ]; then
module=$(echo "$import" | sed -E 's/.*[<"]([^">]+)[">].*/\1/' | sed 's|.*/||' | sed 's/\..*$//')
url=$(get_doc_url "$module" "$doc_lang")
fi
import_escaped=$(echo "$import" | sed 's/|/\\|/g')
import_escaped="${import//|/\\|}"
echo "| \`$import_escaped\` | $count | [docs]($url) |" >>"$DOCS_FILE"
done
echo "" >>"$DOCS_FILE"
@ -624,12 +636,14 @@ else
echo -e "${YELLOW}No per-language files found, using combined analysis${NC}"
if [ -f "$RESULTS_DIR/grep_keywords.txt" ]; then
echo "## Language Keywords" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
echo "| Keyword | Count | Documentation |" >>"$DOCS_FILE"
echo "|---------|-------|---------------|" >>"$DOCS_FILE"
{
echo "## Language Keywords"
echo ""
echo "| Keyword | Count | Documentation |"
echo "|---------|-------|---------------|"
} >>"$DOCS_FILE"
head -$TOP_N "$RESULTS_DIR/grep_keywords.txt" | while read -r count term; do
head -n "$TOP_N" "$RESULTS_DIR/grep_keywords.txt" | while read -r count term; do
[ -z "$term" ] && continue
url=$(get_doc_url "$term" "$PRIMARY_LANG")
echo "| \`$term\` | $count | [docs]($url) |" >>"$DOCS_FILE"
@ -638,12 +652,14 @@ else
fi
if [ -f "$RESULTS_DIR/grep_function_calls.txt" ]; then
echo "## Function/Method Calls" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
echo "| Function | Count | Documentation |" >>"$DOCS_FILE"
echo "|----------|-------|---------------|" >>"$DOCS_FILE"
{
echo "## Function/Method Calls"
echo ""
echo "| Function | Count | Documentation |"
echo "|----------|-------|---------------|"
} >>"$DOCS_FILE"
head -$TOP_N "$RESULTS_DIR/grep_function_calls.txt" | while read -r count term; do
head -n "$TOP_N" "$RESULTS_DIR/grep_function_calls.txt" | while read -r count term; do
[ -z "$term" ] && continue
[[ $term =~ ^(if|for|while|switch|catch)$ ]] && continue
url=$(get_doc_url "$term" "$PRIMARY_LANG")
@ -653,25 +669,29 @@ else
fi
if [ -f "$RESULTS_DIR/grep_imports.txt" ]; then
echo "## Imports/Includes" >>"$DOCS_FILE"
echo "" >>"$DOCS_FILE"
echo "| Import | Count | Documentation |" >>"$DOCS_FILE"
echo "|--------|-------|---------------|" >>"$DOCS_FILE"
{
echo "## Imports/Includes"
echo ""
echo "| Import | Count | Documentation |"
echo "|--------|-------|---------------|"
} >>"$DOCS_FILE"
head -20 "$RESULTS_DIR/grep_imports.txt" | while read -r count import; do
[ -z "$import" ] && continue
module=$(echo "$import" | sed -E 's/.*[<"]([^">]+)[">].*/\1/' | sed 's|.*/||' | sed 's/\..*$//')
url=$(get_doc_url "$module" "$PRIMARY_LANG")
import_escaped=$(echo "$import" | sed 's/|/\\|/g')
import_escaped="${import//|/\\|}"
echo "| \`$import_escaped\` | $count | [docs]($url) |" >>"$DOCS_FILE"
done
echo "" >>"$DOCS_FILE"
fi
fi
echo "" >>"$DOCS_FILE"
echo "---" >>"$DOCS_FILE"
echo "*Generated by analyze_repo.sh + generate_study_materials.sh*" >>"$DOCS_FILE"
{
echo ""
echo "---"
echo "*Generated by analyze_repo.sh + generate_study_materials.sh*"
} >>"$DOCS_FILE"
echo -e "${GREEN}Created: $DOCS_FILE${NC}"
#==============================================================================
@ -694,7 +714,7 @@ EOF
# Generate cards for top keywords
if [ -f "$RESULTS_DIR/grep_keywords.txt" ]; then
echo "# Keywords" >>"$ANKI_FILE"
head -$TOP_N "$RESULTS_DIR/grep_keywords.txt" | while read -r count term; do
head -n "$TOP_N" "$RESULTS_DIR/grep_keywords.txt" | while read -r count term; do
[ -z "$term" ] && continue
url=$(get_doc_url "$term" "$PRIMARY_LANG")
@ -730,9 +750,11 @@ fi
# Generate cards for top functions
if [ -f "$RESULTS_DIR/grep_function_calls.txt" ]; then
echo "" >>"$ANKI_FILE"
echo "# Functions" >>"$ANKI_FILE"
head -$TOP_N "$RESULTS_DIR/grep_function_calls.txt" | while read -r count term; do
{
echo ""
echo "# Functions"
} >>"$ANKI_FILE"
head -n "$TOP_N" "$RESULTS_DIR/grep_function_calls.txt" | while read -r count term; do
[ -z "$term" ] && continue
[[ $term =~ ^(if|for|while|switch|catch)$ ]] && continue
url=$(get_doc_url "$term" "$PRIMARY_LANG")
@ -780,7 +802,7 @@ generate_keywords_with_docs() {
local keywords_file="$RESULTS_DIR/grep_keywords.txt"
[ ! -f "$keywords_file" ] && echo "No keywords found" && return
head -$TOP_N "$keywords_file" | grep -v '^#' | while read -r line; do
head -n "$TOP_N" "$keywords_file" | grep -v '^#' | while read -r line; do
local count
count=$(echo "$line" | awk '{print $1}')
local keyword
@ -797,7 +819,7 @@ generate_functions_with_docs() {
local functions_file="$RESULTS_DIR/grep_function_calls.txt"
[ ! -f "$functions_file" ] && echo "No functions found" && return
head -$TOP_N "$functions_file" | grep -v '^#' | while read -r line; do
head -n "$TOP_N" "$functions_file" | grep -v '^#' | while read -r line; do
local count
count=$(echo "$line" | awk '{print $1}')
local func

View File

@ -110,6 +110,9 @@ install_exercism_cli() {
# Check PATH
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
warn "Add ~/.local/bin to your PATH:"
# Printing a line for the USER to paste into their shell rc: $HOME and
# $PATH must appear literally, not be resolved to this machine's values.
# shellcheck disable=SC2016
echo ' export PATH="$HOME/.local/bin:$PATH"'
fi
}
@ -151,7 +154,11 @@ install_test_runners() {
success "Python: pytest already installed"
else
info "Installing pytest for Python exercises..."
pip3 install --user pytest 2> /dev/null && success "Python: pytest installed" || warn "Python: install pytest manually"
if pip3 install --user pytest 2>/dev/null; then
success "Python: pytest installed"
else
warn "Python: install pytest manually"
fi
fi
fi
@ -256,7 +263,11 @@ show_usage() {
echo ""
echo -e "${CYAN}Batch download (requires API token):${NC}"
echo " # Download first 20 Python exercises:"
# Example commands printed for the user to copy; $(...) and $ex must stay
# literal rather than execute here.
# shellcheck disable=SC2016
echo ' for ex in $(exercism download --track=python 2>&1 | head -20); do'
# shellcheck disable=SC2016
echo ' exercism download --track=python --exercise=$ex'
echo " done"
echo ""

View File

@ -54,6 +54,9 @@ else
fi
# Activate and install packages
# Created at runtime by `python -m venv` above, so there is nothing on disk
# for the linter to follow at check time.
# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"
echo "Installing Python packages for text similarity detection..."
@ -521,6 +524,9 @@ echo " plagcheck thesis_v1.pdf thesis_v2.pdf --detailed"
echo " plagcheck --dir ./student_papers/ --threshold 0.4"
echo ""
echo "Note: Ensure ~/.local/bin is in your PATH:"
# Printed for the user to paste into their shell rc: $HOME and $PATH must
# stay literal rather than resolve to this machine's values.
# shellcheck disable=SC2016
echo ' export PATH="$HOME/.local/bin:$PATH"'
echo ""
echo "=============================================="
@ -528,5 +534,8 @@ echo "=============================================="
# Add to PATH reminder
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
warn "Add ~/.local/bin to your PATH by adding this to ~/.bashrc or ~/.zshrc:"
# Printed for the user to paste into their shell rc: $HOME and $PATH must
# stay literal rather than resolve to this machine's values.
# shellcheck disable=SC2016
echo ' export PATH="$HOME/.local/bin:$PATH"'
fi

View File

@ -887,7 +887,7 @@ main() {
if [ "$lang" = "all" ]; then
lookup_all "$term"
else
result=$(lookup_$lang "$term" 2> /dev/null)
result=$("lookup_$lang" "$term" 2>/dev/null)
if [ -n "$result" ]; then
local file desc
file=$(echo "$result" | cut -d'|' -f1)

View File

@ -25,7 +25,11 @@ ensure_adb_installed() {
if command -v pacman &>/dev/null; then
sudo pacman -S --noconfirm android-tools || die "Failed to install android-tools"
elif command -v apt-get &>/dev/null; then
sudo apt-get update && sudo apt-get install -y adb || die "Failed to install adb"
# `apt-get update && apt-get install ... || die` would also die when the
# update succeeded but the install failed to REPORT - and, worse, skipped
# die entirely if update itself failed. Check each step.
sudo apt-get update || die "Failed to update apt package lists"
sudo apt-get install -y adb || die "Failed to install adb"
elif command -v dnf &>/dev/null; then
sudo dnf install -y android-tools || die "Failed to install android-tools"
else

View File

@ -42,10 +42,12 @@ fix_cloudflare_key() {
if [[ ${expired:-0} -gt 0 ]]; then
log "Refreshing expired Cloudflare WARP GPG key..."
curl -fsSL https://pkg.cloudflareclient.com/pubkey.gpg \
| gpg --yes --dearmor -o "$keyring" 2>/dev/null \
&& log "Cloudflare key refreshed." \
|| log "WARNING: Could not refresh Cloudflare key (network issue?). Skipping."
if curl -fsSL https://pkg.cloudflareclient.com/pubkey.gpg |
gpg --yes --dearmor -o "$keyring" 2>/dev/null; then
log "Cloudflare key refreshed."
else
log "WARNING: Could not refresh Cloudflare key (network issue?). Skipping."
fi
fi
}
@ -66,8 +68,8 @@ fix_wine_legacy_key() {
# Export key to modern location
gpg --no-default-keyring --keyring "$legacy_keyring" \
--export "$wine_key_id" \
| gpg --yes --dearmor -o "$modern_keyring" 2>/dev/null
--export "$wine_key_id" |
gpg --yes --dearmor -o "$modern_keyring" 2>/dev/null
# Remove from legacy keyring (suppress the deprecation warning)
apt-key del "$wine_key_id" >/dev/null 2>&1 || true

View File

@ -38,8 +38,8 @@ ANDROID_GUARDIAN_DIR="$SKIP_MAIN_GUARDIAN_DIR" \
ANDROID_GUARDIAN_MODULE_DIR="$TMP_DIR/skip-main-module" \
sh "$TARGET_SCRIPT"
[[ ! -d "$SKIP_MAIN_GUARDIAN_DIR" ]] \
|| fail 'skip-main should prevent guardian boot setup side effects'
[[ ! -d "$SKIP_MAIN_GUARDIAN_DIR" ]] ||
fail 'skip-main should prevent guardian boot setup side effects'
printf 'Checking guardian loop cadence constants...\n'
hosts_ticks=$(grep '^HOSTS_CHECK_EVERY_TICKS=' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" | cut -d= -f2)
@ -51,19 +51,22 @@ assert_equals '12' "$apps_ticks" 'blocked-app scan should run every 12 ticks'
assert_equals '5' "$sleep_seconds" 'guardian loop should keep the 5 second base sleep'
printf 'Checking guardian loop protects module every tick...\n'
grep -q 'protect_module' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" \
|| fail 'guardian loop must always protect the module each tick'
grep -q 'protect_module' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" ||
fail 'guardian loop must always protect the module each tick'
printf 'Checking blocked-app scans are cached per pass...\n'
grep -q 'installed_packages=$(pm list packages 2>/dev/null)' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" \
|| fail 'guardian service should cache installed packages once per blocked-app scan'
# Literal search pattern: the $ must reach grep as text, not be expanded
# by this shell.
# shellcheck disable=SC2016
grep -q 'installed_packages=$(pm list packages 2>/dev/null)' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" ||
fail 'guardian service should cache installed packages once per blocked-app scan'
if grep -q 'pm list packages 2>/dev/null | grep -q' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh"; then
fail 'guardian service should not re-run pm list packages through grep for every blocked app'
fi
printf 'Checking guardian loop uses skip-main guard for tests...\n'
grep -q 'ANDROID_GUARDIAN_SKIP_MAIN' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" \
|| fail 'guardian service should support skip-main testing'
grep -q 'ANDROID_GUARDIAN_SKIP_MAIN' "$WORKTREE/scripts/periodic_background/utils/android_guardian/service.sh" ||
fail 'guardian service should support skip-main testing'
printf 'android_guardian service regression checks passed.\n'

View File

@ -87,6 +87,9 @@ assert_order "$WRAPPER_FILE" 'if ! check_and_handle_db_lock "$@"; then' 'if shou
assert_contains "$WRAPPER_FILE" 'manual_guard_lib_fallback=1' \
"wrapper tracks whether manual hosts guard fallback was used"
# Literal source text being searched for; expanding $SCRIPT_DIR /
# $LOCK_LIB_DEST here would search for this machine's values instead.
# shellcheck disable=SC2016
assert_contains "$INSTALLER_FILE" 'install -m 755 "$SCRIPT_DIR/pacman-hooks/hosts-guard-common.sh" /usr/local/share/hosts-guard/' \
"installer deploys shared hosts guard hook helpers"

View File

@ -202,6 +202,9 @@ fi
# Test: the lock library is covered by the integrity manifest
echo "[TEST] Verifying installer checksums the lock library..."
# Literal source text being searched for; expanding $SCRIPT_DIR /
# $LOCK_LIB_DEST here would search for this machine's values instead.
# shellcheck disable=SC2016
if grep -qF 'sha256sum "$LOCK_LIB_DEST"' "$WRAPPER_DIR/install_pacman_wrapper.sh"; then
echo "✓ Lock library is included in the integrity manifest"
else

View File

@ -116,6 +116,10 @@ run_dbus_throttle_case() {
: >"$counter_file"
# The `bash -c` body below is a script for a CHILD shell - $1,
# $TEST_CHECK_INTERVAL, $COUNTER_FILE and ${mock_ts[...]} must reach it
# UNEXPANDED and be evaluated there. Single quotes are load-bearing.
# shellcheck disable=SC2016
calls=$(env -i PATH="$BIN_DIR" SHUTDOWN_TIMER_MONITOR_SKIP_MAIN=1 MOCK_BUSCTL_LINES="day-specific-shutdown.timer\nday-specific-shutdown.timer\nday-specific-shutdown.timer" MOCK_TS_SEQUENCE="$ts_sequence" COUNTER_FILE="$counter_file" TEST_CHECK_INTERVAL="$check_interval" /bin/bash -c '
source "$1"
CHECK_INTERVAL="$TEST_CHECK_INTERVAL"
@ -167,25 +171,32 @@ wait_elapsed=$(env -i PATH="/usr/bin:/bin" SHUTDOWN_TIMER_MONITOR_SKIP_MAIN=1 /b
assert_equals '1' "$wait_elapsed" 'wait_seconds should not return immediately on /dev/null stdin'
printf 'Checking installer template stays in sync with the event-driven monitor...\n'
grep -Fq 'monitor_with_dbus()' "$SETUP_SCRIPT" \
|| fail 'setup_midnight_shutdown.sh should install the D-Bus monitor helper'
grep -Fq 'start_monitoring()' "$SETUP_SCRIPT" \
|| fail 'setup_midnight_shutdown.sh should install the start_monitoring dispatcher'
grep -Fq 'if command -v busctl &>/dev/null; then' "$SETUP_SCRIPT" \
|| fail 'setup_midnight_shutdown.sh should prefer busctl when available'
grep -Fq 'current_epoch now_ts' "$SETUP_SCRIPT" \
|| fail 'setup_midnight_shutdown.sh should use out-var epoch helper in D-Bus throttling path'
grep -Fq 'monitor_with_dbus()' "$SETUP_SCRIPT" ||
fail 'setup_midnight_shutdown.sh should install the D-Bus monitor helper'
grep -Fq 'start_monitoring()' "$SETUP_SCRIPT" ||
fail 'setup_midnight_shutdown.sh should install the start_monitoring dispatcher'
grep -Fq 'if command -v busctl &>/dev/null; then' "$SETUP_SCRIPT" ||
fail 'setup_midnight_shutdown.sh should prefer busctl when available'
grep -Fq 'current_epoch now_ts' "$SETUP_SCRIPT" ||
fail 'setup_midnight_shutdown.sh should use out-var epoch helper in D-Bus throttling path'
# Searching for this literal source text; expanding it would run
# current_epoch and grep for its output instead.
# shellcheck disable=SC2016
if grep -Fq 'now_ts=$(current_epoch)' "$SETUP_SCRIPT"; then
fail 'setup_midnight_shutdown.sh should avoid subshell epoch capture in D-Bus path'
fi
# Literal source text, as above.
# shellcheck disable=SC2016
if grep -Fq 'now_ts=$(current_epoch)' "$TARGET_SCRIPT"; then
fail 'runtime shutdown monitor should avoid subshell epoch capture in D-Bus path'
fi
grep -Fq 'OnUnitActiveSec=300' "$SETUP_SCRIPT" \
|| fail 'setup_midnight_shutdown.sh should run watchdog timer at 300s cadence'
grep -Fq 'wait_seconds()' "$SETUP_SCRIPT" \
|| fail 'setup_midnight_shutdown.sh should install builtin wait helper in polling fallback'
grep -Fq 'wait_seconds "$CHECK_INTERVAL"' "$TARGET_SCRIPT" \
|| fail 'runtime shutdown monitor polling fallback should use builtin wait helper'
grep -Fq 'OnUnitActiveSec=300' "$SETUP_SCRIPT" ||
fail 'setup_midnight_shutdown.sh should run watchdog timer at 300s cadence'
grep -Fq 'wait_seconds()' "$SETUP_SCRIPT" ||
fail 'setup_midnight_shutdown.sh should install builtin wait helper in polling fallback'
# Literal source text, as above.
# shellcheck disable=SC2016
grep -Fq 'wait_seconds "$CHECK_INTERVAL"' "$TARGET_SCRIPT" ||
fail 'runtime shutdown monitor polling fallback should use builtin wait helper'
printf 'shutdown-timer-monitor.sh regression checks passed.\n'

View File

@ -23,30 +23,36 @@ logger_template=$(
[[ -n $logger_template ]] || fail 'could not extract nvidia-pmon-logger template from installer'
printf 'Checking pmon logger template avoids read -t busy-loop pattern...\n'
! grep -q 'read -r -t' <<< "$logger_template" \
|| fail 'logger template must not use read -t as sleep surrogate'
! grep -q 'read -r -t' <<<"$logger_template" ||
fail 'logger template must not use read -t as sleep surrogate'
# The template used to poll with `sleep 60` until the day changed. It now
# sleeps exactly once, until the next midnight, and blocks on `wait` for the
# pmon child — strictly fewer wakeups. Assert that property rather than the
# old literal, so an accidental return to polling still fails the test.
printf 'Checking pmon logger template sleeps until rollover rather than polling...\n'
grep -q 'sleep "\$(seconds_until_next_day)"' <<< "$logger_template" \
|| fail 'logger template must sleep until the next day boundary'
# Literal search pattern: the $ must reach grep as text, not be expanded
# by this shell.
# shellcheck disable=SC2016
grep -q 'sleep "\$(seconds_until_next_day)"' <<<"$logger_template" ||
fail 'logger template must sleep until the next day boundary'
grep -q 'seconds_until_next_day()' <<< "$logger_template" \
|| fail 'logger template must define seconds_until_next_day'
grep -q 'seconds_until_next_day()' <<<"$logger_template" ||
fail 'logger template must define seconds_until_next_day'
printf 'Checking pmon logger template blocks on wait instead of spinning...\n'
grep -qE '^\s*wait "\$pmon_pid"' <<< "$logger_template" \
|| fail 'logger template must block on wait for the pmon child'
# Literal search pattern: the $ must reach grep as text, not be expanded
# by this shell.
# shellcheck disable=SC2016
grep -qE '^\s*wait "\$pmon_pid"' <<<"$logger_template" ||
fail 'logger template must block on wait for the pmon child'
printf 'Checking pmon logger template uses fork-free date builtin...\n'
grep -q "printf '%(%Y%m%d)T' -1" <<< "$logger_template" \
|| fail 'logger template must use bash printf time builtin for current day'
grep -q "printf '%(%Y%m%d)T' -1" <<<"$logger_template" ||
fail 'logger template must use bash printf time builtin for current day'
printf 'Checking pmon logger template avoids external date command...\n'
! grep -q 'date +%Y%m%d' <<< "$logger_template" \
|| fail 'logger template must not call external date command in hot path'
! grep -q 'date +%Y%m%d' <<<"$logger_template" ||
fail 'logger template must not call external date command in hot path'
printf 'Usage monitoring installer efficiency tests passed.\n'

View File

@ -51,7 +51,12 @@ done
FIX_MODE=false
QUICK_MODE=false
REPORT_MODE=false
# Kept as BOTH a string and an array on purpose: run_tool() takes a single
# command STRING (it evals it), so the string form has to stay, while the
# handful of direct invocations below need proper argument splitting that
# only an array gives -- an unquoted "${TARGET_FILES}" there would also glob.
TARGET_FILES=""
TARGET_FILES_ARR=()
while [[ $# -gt 0 ]]; do
case $1 in
@ -85,6 +90,7 @@ while [[ $# -gt 0 ]]; do
;;
*)
TARGET_FILES="${TARGET_FILES} $1"
TARGET_FILES_ARR+=("$1")
shift
;;
esac
@ -93,6 +99,7 @@ done
# If no target specified, use default paths
if [[ -z "${TARGET_FILES}" ]]; then
TARGET_FILES="${PYTHON_PATHS[*]}"
TARGET_FILES_ARR=("${PYTHON_PATHS[@]}")
fi
# Create reports directory if needed
@ -269,14 +276,14 @@ if check_tool radon; then
print_subheader "Running radon (complexity analysis)..."
echo ""
echo -e "${MAGENTA}Cyclomatic Complexity:${NC}"
radon cc -a -s ${TARGET_FILES} || true
radon cc -a -s "${TARGET_FILES_ARR[@]}" || true
echo ""
echo -e "${MAGENTA}Maintainability Index:${NC}"
radon mi -s ${TARGET_FILES} || true
radon mi -s "${TARGET_FILES_ARR[@]}" || true
if [[ "${REPORT_MODE}" == true ]]; then
radon cc -a -s ${TARGET_FILES} > "${PROJECT_ROOT}/lint-reports/radon-cc.txt" 2>&1 || true
radon mi -s ${TARGET_FILES} > "${PROJECT_ROOT}/lint-reports/radon-mi.txt" 2>&1 || true
radon cc -a -s "${TARGET_FILES_ARR[@]}" >"${PROJECT_ROOT}/lint-reports/radon-cc.txt" 2>&1 || true
radon mi -s "${TARGET_FILES_ARR[@]}" >"${PROJECT_ROOT}/lint-reports/radon-mi.txt" 2>&1 || true
fi
fi
@ -299,7 +306,7 @@ fi
# ==============================================================================
if [[ "${FIX_MODE}" == true ]] && check_tool autoflake; then
print_subheader "Running autoflake (removing unused imports)..."
find ${TARGET_FILES} -name "*.py" -type f -exec autoflake --in-place --remove-all-unused-imports --remove-unused-variables {} \;
find "${TARGET_FILES_ARR[@]}" -name "*.py" -type f -exec autoflake --in-place --remove-all-unused-imports --remove-unused-variables {} \;
print_success "autoflake completed"
fi
@ -308,7 +315,7 @@ fi
# ==============================================================================
if [[ "${FIX_MODE}" == true ]] && check_tool pyupgrade; then
print_subheader "Running pyupgrade (upgrading syntax to Python 3.10+)..."
find ${TARGET_FILES} -name "*.py" -type f -exec pyupgrade --py310-plus {} \;
find "${TARGET_FILES_ARR[@]}" -name "*.py" -type f -exec pyupgrade --py310-plus {} \;
print_success "pyupgrade completed"
fi

View File

@ -66,8 +66,8 @@ diagnose_polling_scripts() {
# Pattern 1: while true with sleep (no event-driven check)
echo "1. Polling loops (while true + sleep):" >&2
set +e
grep -r "while true\|while :" --include="*.sh" "$SCRIPT_DIR" 2>/dev/null \
| grep -v "Binary" | grep -v ".git" | head -5
grep -r "while true\|while :" --include="*.sh" "$SCRIPT_DIR" 2>/dev/null |
grep -v "Binary" | grep -v ".git" | head -5
set -e
issues_found=$((issues_found + 1))
echo "" >&2
@ -75,8 +75,11 @@ diagnose_polling_scripts() {
# Pattern 2: $(date +...) calls in loops (fork-heavy)
echo "2. Excessive date calls (each forks a process):" >&2
set +e
grep -r '\$(date' --include="*.sh" "$SCRIPT_DIR" 2>/dev/null \
| grep -v "Binary" | grep -v ".git" | head -5
# Literal search pattern: the $ must reach grep as text, not be expanded
# by this shell.
# shellcheck disable=SC2016
grep -r '\$(date' --include="*.sh" "$SCRIPT_DIR" 2>/dev/null |
grep -v "Binary" | grep -v ".git" | head -5
set -e
issues_found=$((issues_found + 1))
echo "" >&2
@ -84,8 +87,8 @@ diagnose_polling_scripts() {
# Pattern 3: pgrep/xdotool in loops
echo "3. Process inspection in loops (pgrep, xdotool):" >&2
set +e
grep -r "while.*pgrep\|while.*xdotool\|pgrep.*while" --include="*.sh" "$SCRIPT_DIR" 2>/dev/null \
| grep -v "Binary" | grep -v ".git" | head -5
grep -r "while.*pgrep\|while.*xdotool\|pgrep.*while" --include="*.sh" "$SCRIPT_DIR" 2>/dev/null |
grep -v "Binary" | grep -v ".git" | head -5
set -e
issues_found=$((issues_found + 1))
echo "" >&2
@ -108,8 +111,8 @@ diagnose_polling_scripts() {
# Pattern 5: sleep with very short intervals
echo "5. Aggressive polling (sleep < 1s):" >&2
set +e
grep -rE "sleep 0\.[0-9]|sleep 0[^0-9]" --include="*.sh" "$SCRIPT_DIR" 2>/dev/null \
| grep -v "Binary" | grep -v ".git" | head -5
grep -rE "sleep 0\.[0-9]|sleep 0[^0-9]" --include="*.sh" "$SCRIPT_DIR" 2>/dev/null |
grep -v "Binary" | grep -v ".git" | head -5
set -e
issues_found=$((issues_found + 1))
echo "" >&2

View File

@ -11,7 +11,9 @@ errors=0
files_checked=0
# Patterns to detect (these are red flags for fork storms)
# shellcheck disable=SC2034
# These are regex patterns held literally -- the $( and ` inside them are
# part of what we search FOR, so they must not be expanded here.
# shellcheck disable=SC2034,SC2016
declare -A patterns=(
['while_true_with_sleep']='while\s+(true|:).*sleep'
['date_in_loop']='while.*date|for.*date'

View File

@ -7,12 +7,12 @@
#
# Safe by default: nothing is deleted without --clean AND user confirmation.
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'
RED=$'\033[0;31m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[1;33m'
CYAN=$'\033[0;36m'
BOLD=$'\033[1m'
RESET=$'\033[0m'
CLEAN=false
if [[ "${1:-}" == "--clean" ]]; then
@ -76,14 +76,14 @@ try_clean() {
shift
if confirm "$prompt"; then
"$@"
printf "${GREEN} ✓ Done${RESET}\n"
printf "%s ✓ Done%s\n" "${GREEN}" "${RESET}"
fi
return 0
}
# ───────────────────── checks ─────────────────────
printf "\n${BOLD}=== Disk Cleanup Analysis ===${RESET}\n\n"
printf "\n%s=== Disk Cleanup Analysis ===%s\n\n" "${BOLD}" "${RESET}"
printf "${BOLD}%-40s %10s${RESET}\n" "Category" "Reclaimable"
printf '%s\n' "$(printf '%.0s─' {1..60})"
@ -100,7 +100,7 @@ fi
pacman_cache_size=$(dir_size_kb "/var/cache/pacman/pkg")
if ((pacman_cache_size > 0)); then
if command -v paccache &>/dev/null; then
pkg_count=$(ls /var/cache/pacman/pkg/ 2>/dev/null | wc -l)
pkg_count=$(find /var/cache/pacman/pkg/ -maxdepth 1 -type f -name '*.pkg.tar*' 2>/dev/null | wc -l)
report "Pacman cache ($pkg_count pkgs)" "$pacman_cache_size" \
"sudo paccache -rk2"
try_clean "Clean pacman cache (keep last 2 versions)?" \
@ -234,8 +234,8 @@ if [[ -n "$orphans" ]]; then
orphan_count=$(echo "$orphans" | wc -l)
fi
if ((orphan_count > 0)); then
orphan_size=$(echo "$orphans" | xargs pacman -Qi 2>/dev/null \
| awk '/Installed Size/{
orphan_size=$(echo "$orphans" | xargs pacman -Qi 2>/dev/null |
awk '/Installed Size/{
size=$4; unit=$5;
if (unit ~ /GiB/) total += size*1048576;
else if (unit ~ /MiB/) total += size*1024;
@ -246,7 +246,7 @@ if (( orphan_count > 0 )); then
if confirm "Remove $orphan_count orphan packages?"; then
# shellcheck disable=SC2046
sudo pacman -Rns $(pacman -Qdtq) --noconfirm
printf "${GREEN} ✓ Orphans removed${RESET}\n"
printf "%s ✓ Orphans removed%s\n" "${GREEN}" "${RESET}"
fi
fi
@ -271,8 +271,8 @@ if [[ -d "$aur_dir" ]]; then
old_archives_kb=$(find "$aur_dir" \
\( -name "*.pkg.tar.zst" -o -name "*.tar.gz" -o -name "*.tar.xz" \
-o -name "*.zip" -o -name "*.tar.bz2" \) \
-mtime +30 -printf '%k\n' 2>/dev/null \
| awk '{t+=$1} END{print t+0}')
-mtime +30 -printf '%k\n' 2>/dev/null |
awk '{t+=$1} END{print t+0}')
if ((old_archives_kb > 0)); then
report "AUR old archives (>30d)" "$old_archives_kb" \
"find ~/aur '*.pkg.tar.zst' -mtime +30 -delete"
@ -281,15 +281,14 @@ if [[ -d "$aur_dir" ]]; then
\( -name "*.pkg.tar.zst" -o -name "*.tar.gz" -o -name "*.tar.xz" \
-o -name "*.zip" -o -name "*.tar.bz2" \) \
-mtime +30 -delete
printf "${GREEN} ✓ Old AUR archives deleted${RESET}\n"
printf "%s ✓ Old AUR archives deleted%s\n" "${GREEN}" "${RESET}"
fi
fi
fi
# ───────────────────── report-only items ─────────────────────
printf "\n${BOLD}--- Report-only (manual review needed) ---${RESET}\n"
printf "\n%s--- Report-only (manual review needed) ---%s\n" "${BOLD}" "${RESET}"
for manual_entry in \
"$HOME/Downloads/too_big:~/Downloads/too_big" \
"$HOME/Downloads:~/Downloads total" \
@ -325,6 +324,6 @@ if (( TOTAL_RECLAIMABLE > 0 )); then
fi
if ! $CLEAN; then
printf "\n${CYAN}Run with --clean to interactively clean each category.${RESET}\n"
printf "\n%sRun with --clean to interactively clean each category.%s\n" "${CYAN}" "${RESET}"
fi
printf "\n"

View File

@ -15,6 +15,11 @@ SCRIPT_DIR="${FOCUS_MODE_SCRIPT_DIR:-$(cd "$(dirname "$0")" && pwd)}"
if [ ! -f "$SCRIPT_DIR/config_secrets.sh" ] && [ -f "/data/local/tmp/focus_mode/config_secrets.sh" ]; then
SCRIPT_DIR="/data/local/tmp/focus_mode"
fi
# config_secrets.sh is deliberately untracked (it holds secrets, see
# .gitignore) and is created per-machine / pushed to the phone at deploy
# time. It does not exist in a clean checkout, so the linter cannot follow
# it there -- which is exactly what CI lints.
# shellcheck disable=SC1091
. "$SCRIPT_DIR/config_secrets.sh"
# --- Radius in meters ---

View File

@ -17,12 +17,16 @@ set -euo pipefail
PHONE_IP="${1:-}"
ACTION="${2:---deploy}"
REMOTE_DIR="/data/local/tmp/focus_mode"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Deliberately NOT named SCRIPT_DIR: config.sh (sourced below, at top
# level) assigns SCRIPT_DIR itself and may repoint it at the on-device
# path /data/local/tmp/focus_mode. Every path here must stay anchored to
# the checkout deploy.sh runs from.
DEPLOY_DIR="$(cd "$(dirname "$0")" && pwd)"
NEEDS_GPS_FETCH=0 # set to 1 by check_coords when local coords are placeholder
# Source shared config constants (BROWSER_PACKAGES, REMOTE_DIR, etc.)
# shellcheck source=config.sh
. "$SCRIPT_DIR/config.sh"
. "$DEPLOY_DIR/config.sh"
ADB_TARGET=()
@ -84,8 +88,8 @@ check_adb() {
check_coords() {
local lat lon
lat="$(grep '^.*HOME_LAT=' "$SCRIPT_DIR/config.sh" "$SCRIPT_DIR/config_secrets.sh" 2>/dev/null | tail -1 | cut -d'"' -f2)"
lon="$(grep '^.*HOME_LON=' "$SCRIPT_DIR/config.sh" "$SCRIPT_DIR/config_secrets.sh" 2>/dev/null | tail -1 | cut -d'"' -f2)"
lat="$(grep '^.*HOME_LAT=' "$DEPLOY_DIR/config.sh" "$DEPLOY_DIR/config_secrets.sh" 2>/dev/null | tail -1 | cut -d'"' -f2)"
lon="$(grep '^.*HOME_LON=' "$DEPLOY_DIR/config.sh" "$DEPLOY_DIR/config_secrets.sh" 2>/dev/null | tail -1 | cut -d'"' -f2)"
if [ "$lat" = "0.000000" ] && [ "$lon" = "0.000000" ]; then
echo "ERROR: Home coordinates not set (all zeros)."
exit 1
@ -176,10 +180,10 @@ fetch_home_coords_from_phone() {
waited=$((waited + 3))
# Format on Android 10+: " last location=Location[fused LAT,LON ...]"
local raw
raw="$(adb_cmd shell dumpsys location 2>/dev/null \
| grep 'last location=Location\[' \
| grep -oE '[+-]?[0-9]+\.[0-9]+,[+-]?[0-9]+\.[0-9]+' \
| head -1 || true)"
raw="$(adb_cmd shell dumpsys location 2>/dev/null |
grep 'last location=Location\[' |
grep -oE '[+-]?[0-9]+\.[0-9]+,[+-]?[0-9]+\.[0-9]+' |
head -1 || true)"
[[ -n "$raw" ]] && coords="$raw"
printf '.' >&2
done
@ -367,23 +371,23 @@ do_deploy() {
adb_root "chmod 777 /data/local/tmp/focus_stage"
echo "[4/7] Uploading scripts..."
adb_cmd push "$SCRIPT_DIR/config.sh" "/data/local/tmp/focus_stage/config.sh"
adb_cmd push "$SCRIPT_DIR/focus_daemon.sh" "/data/local/tmp/focus_stage/focus_daemon.sh"
adb_cmd push "$SCRIPT_DIR/focus_ctl.sh" "/data/local/tmp/focus_stage/focus_ctl.sh"
adb_cmd push "$SCRIPT_DIR/hosts_enforcer.sh" "/data/local/tmp/focus_stage/hosts_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/dns_enforcer.sh" "/data/local/tmp/focus_stage/dns_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/launcher_enforcer.sh" "/data/local/tmp/focus_stage/launcher_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/curfew_enforcer.sh" "/data/local/tmp/focus_stage/curfew_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/tether_enforcer.sh" "/data/local/tmp/focus_stage/tether_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/workout_detector.sh" "/data/local/tmp/focus_stage/workout_detector.sh"
adb_cmd push "$SCRIPT_DIR/magisk_service.sh" "/data/local/tmp/focus_stage/99-focus-mode.sh"
adb_cmd push "$DEPLOY_DIR/config.sh" "/data/local/tmp/focus_stage/config.sh"
adb_cmd push "$DEPLOY_DIR/focus_daemon.sh" "/data/local/tmp/focus_stage/focus_daemon.sh"
adb_cmd push "$DEPLOY_DIR/focus_ctl.sh" "/data/local/tmp/focus_stage/focus_ctl.sh"
adb_cmd push "$DEPLOY_DIR/hosts_enforcer.sh" "/data/local/tmp/focus_stage/hosts_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/dns_enforcer.sh" "/data/local/tmp/focus_stage/dns_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/launcher_enforcer.sh" "/data/local/tmp/focus_stage/launcher_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/curfew_enforcer.sh" "/data/local/tmp/focus_stage/curfew_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/tether_enforcer.sh" "/data/local/tmp/focus_stage/tether_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/workout_detector.sh" "/data/local/tmp/focus_stage/workout_detector.sh"
adb_cmd push "$DEPLOY_DIR/magisk_service.sh" "/data/local/tmp/focus_stage/99-focus-mode.sh"
# ---- sqlite3 binary for workout_detector.sh ----
# Stored outside the repo (binary-files policy). Built once via the NDK
# against the SQLite amalgamation; see workout_detector.sh comments for
# the recipe. ~1.6 MB stripped, aarch64, PIE, dynamically linked against
# bionic (Android 30+).
SQLITE3_BIN="$SCRIPT_DIR/../../testsAndMisc_binaries/phone_focus_mode/sqlite3"
SQLITE3_BIN="$DEPLOY_DIR/../../testsAndMisc_binaries/phone_focus_mode/sqlite3"
if [ -f "$SQLITE3_BIN" ]; then
echo " Uploading sqlite3 binary ($(stat -c%s "$SQLITE3_BIN") bytes)..."
adb_cmd push "$SQLITE3_BIN" "/data/local/tmp/focus_stage/sqlite3"
@ -394,7 +398,7 @@ do_deploy() {
# Generate and upload the canonical hosts file (StevenBlack + custom entries).
# This mirrors what linux_configuration/hosts/install.sh installs on the PC.
HOSTS_GENERATOR="$SCRIPT_DIR/../linux_configuration/scripts/periodic_background/hosts/generate_hosts_file.sh"
HOSTS_GENERATOR="$DEPLOY_DIR/../linux_configuration/scripts/periodic_background/hosts/generate_hosts_file.sh"
if [ -f "$HOSTS_GENERATOR" ]; then
chmod +x "$HOSTS_GENERATOR" 2>/dev/null || true
echo " Generating canonical hosts file..."
@ -417,10 +421,13 @@ do_deploy() {
# so the generator and the runtime always agree on the domain set.
UNBLOCK_DOMAINS="$(
# shellcheck disable=SC1091
( . "$SCRIPT_DIR/config.sh" >/dev/null 2>&1; printf '%s\n' "$WORKOUT_UNBLOCK_DOMAINS" ) \
| sed 's/[[:space:]]\{1,\}/\n/g' \
| grep -vE '^[[:space:]]*(#|$)' \
| sort -u
(
. "$DEPLOY_DIR/config.sh" >/dev/null 2>&1
printf '%s\n' "$WORKOUT_UNBLOCK_DOMAINS"
) |
sed 's/[[:space:]]\{1,\}/\n/g' |
grep -vE '^[[:space:]]*(#|$)' |
sort -u
)"
if [ -n "$UNBLOCK_DOMAINS" ]; then
# Build an awk regex of exact-match domains anchored as the
@ -428,8 +435,8 @@ do_deploy() {
# followed by aliases). We strip any line whose first non-IP
# token matches one of the unblock domains.
WORKOUT_UNBLOCK_DOMAINS="$UNBLOCK_DOMAINS" \
python3 "$SCRIPT_DIR/strip_workout_hosts.py" "$HOSTS_TMP" "$HOSTS_WORKOUT_TMP" \
|| cp "$HOSTS_TMP" "$HOSTS_WORKOUT_TMP"
python3 "$DEPLOY_DIR/strip_workout_hosts.py" "$HOSTS_TMP" "$HOSTS_WORKOUT_TMP" ||
cp "$HOSTS_TMP" "$HOSTS_WORKOUT_TMP"
workout_hash="$(compute_file_hash "$HOSTS_WORKOUT_TMP")"
printf '%s\n' "$workout_hash" >"$HOSTS_WORKOUT_SHA_TMP"
stripped_lines=$(($(wc -l <"$HOSTS_TMP") - $(wc -l <"$HOSTS_WORKOUT_TMP")))
@ -475,7 +482,7 @@ do_deploy() {
fi
else
echo " Pushing config_secrets.sh (first install)..."
adb_cmd push "$SCRIPT_DIR/config_secrets.sh" "/data/local/tmp/focus_stage/config_secrets.sh"
adb_cmd push "$DEPLOY_DIR/config_secrets.sh" "/data/local/tmp/focus_stage/config_secrets.sh"
adb_root "cp /data/local/tmp/focus_stage/config_secrets.sh $REMOTE_DIR/config_secrets.sh"
fi
@ -493,7 +500,7 @@ do_deploy() {
adb_root "cp /data/local/tmp/focus_stage/sqlite3 $REMOTE_DIR/sqlite3"
adb_root "chmod 0755 $REMOTE_DIR/sqlite3"
fi
if grep -q '^export FOCUS_BOOT_AUTOSTART=1' "$SCRIPT_DIR/config.sh"; then
if grep -q '^export FOCUS_BOOT_AUTOSTART=1' "$DEPLOY_DIR/config.sh"; then
adb_root "cp /data/local/tmp/focus_stage/99-focus-mode.sh /data/adb/service.d/99-focus-mode.sh"
else
adb_root "rm -f /data/adb/service.d/99-focus-mode.sh /data/adb/service.d/99-focus-mode.sh.disabled"
@ -555,6 +562,12 @@ do_deploy() {
# Flush in-process DNS caches of browsers. Apps like Firefox and Chrome
# cache resolved IPs internally and bypass /etc/hosts until restarted.
echo " Flushing browser DNS caches..."
# BROWSER_PACKAGES is set by the top-level `. config.sh` above and is never
# modified. shellcheck only flags it because config.sh is ALSO re-sourced
# inside a subshell further up (to re-read WORKOUT_UNBLOCK_DOMAINS from the
# freshly-staged copy); that subshell's assignments are discarded by design.
# The unquoted expansion is the intended word split over the package list.
# shellcheck disable=SC2031
for _pkg in $BROWSER_PACKAGES; do
[ -n "$_pkg" ] || continue
adb_root "am force-stop '$_pkg' 2>/dev/null; true"
@ -575,7 +588,7 @@ do_deploy() {
echo "[5/7] Setting permissions..."
adb_root "chmod 755 $REMOTE_DIR/config.sh $REMOTE_DIR/focus_daemon.sh $REMOTE_DIR/focus_ctl.sh $REMOTE_DIR/hosts_enforcer.sh $REMOTE_DIR/dns_enforcer.sh $REMOTE_DIR/launcher_enforcer.sh $REMOTE_DIR/curfew_enforcer.sh $REMOTE_DIR/tether_enforcer.sh $REMOTE_DIR/workout_detector.sh" || true
if grep -q '^export FOCUS_BOOT_AUTOSTART=1' "$SCRIPT_DIR/config.sh"; then
if grep -q '^export FOCUS_BOOT_AUTOSTART=1' "$DEPLOY_DIR/config.sh"; then
adb_root "chmod 755 /data/adb/service.d/99-focus-mode.sh"
fi
adb_root "touch $REMOTE_DIR/disabled_by_focus.txt $REMOTE_DIR/focus_mode.log $REMOTE_DIR/hosts_enforcer.log $REMOTE_DIR/dns_enforcer.log $REMOTE_DIR/launcher_enforcer.log $REMOTE_DIR/tether_enforcer.log $REMOTE_DIR/workout_detector.log"
@ -645,7 +658,7 @@ do_deploy() {
sleep 10
# ---- Companion status notification app ----
APP_DIR="$SCRIPT_DIR/focus_status_app"
APP_DIR="$DEPLOY_DIR/focus_status_app"
APK="$APP_DIR/build/focus_status.apk"
if [ -d "$APP_DIR" ]; then
echo "[7/7] Building & installing companion status-notification app..."
@ -679,8 +692,8 @@ do_deploy() {
adb_cmd shell pm grant com.kuhy.focusstatus android.permission.POST_NOTIFICATIONS >/dev/null 2>&1 || true
# Pre-approve Magisk SU so the app never shows the approval prompt.
APP_UID="$(
adb_cmd shell dumpsys package com.kuhy.focusstatus 2>/dev/null \
| awk 'match($0, /userId=[0-9]+/) {print substr($0, RSTART + 7, RLENGTH - 7); exit}'
adb_cmd shell dumpsys package com.kuhy.focusstatus 2>/dev/null |
awk 'match($0, /userId=[0-9]+/) {print substr($0, RSTART + 7, RLENGTH - 7); exit}'
)"
if [ -n "$APP_UID" ]; then
adb_cmd shell "su -c 'magisk --sqlite \"INSERT OR REPLACE INTO policies (uid,policy,until,logging,notification) VALUES ($APP_UID,2,0,1,1)\"'" >/dev/null 2>&1 || true
@ -788,7 +801,10 @@ check_ip
case "$ACTION" in
--deploy | "") do_deploy ;;
--status) do_control "status" ;;
--log) connect_adb; adb_root "sh $REMOTE_DIR/focus_ctl.sh log 100" ;;
--log)
connect_adb
adb_root "sh $REMOTE_DIR/focus_ctl.sh log 100"
;;
--stop) do_control "stop" ;;
--start) do_control "start" ;;
--restart) do_control "restart" ;;
@ -798,11 +814,20 @@ case "$ACTION" in
--pull-log) do_pull_log ;;
--find-pkg) do_find_pkg "$@" ;;
--hosts-status) do_control "hosts-status" ;;
--hosts-log) connect_adb; adb_root "sh $REMOTE_DIR/focus_ctl.sh hosts-log 100" ;;
--hosts-log)
connect_adb
adb_root "sh $REMOTE_DIR/focus_ctl.sh hosts-log 100"
;;
--launcher-status) do_control "launcher-status" ;;
--launcher-log) connect_adb; adb_root "sh $REMOTE_DIR/focus_ctl.sh launcher-log 100" ;;
--launcher-log)
connect_adb
adb_root "sh $REMOTE_DIR/focus_ctl.sh launcher-log 100"
;;
--capture-coords) do_capture_coords ;;
--snapshot-launcher) do_snapshot_launcher ;;
--install-aurora) do_install_aurora ;;
*) echo "Unknown action: $ACTION"; usage ;;
*)
echo "Unknown action: $ACTION"
usage
;;
esac

View File

@ -198,6 +198,10 @@ chain_intact() {
enforce_iptables() {
if command -v iptables >/dev/null 2>&1; then
# Intentional word split: expected_rule_count() iterates "$@" over the
# configured IP list. This runs under /system/bin/sh on the phone, where
# arrays do not exist, so an unquoted expansion is the POSIX way to do it.
# shellcheck disable=SC2086
if chain_intact iptables "$(expected_rule_count $DNS_DOH_IPV4)"; then
:
elif ensure_chain iptables && fill_chain_v4; then
@ -205,6 +209,8 @@ enforce_iptables() {
fi
fi
if command -v ip6tables >/dev/null 2>&1; then
# Intentional word split, as above.
# shellcheck disable=SC2086
if chain_intact ip6tables "$(expected_rule_count $DNS_DOH_IPV6)"; then
:
elif ensure_chain ip6tables && fill_chain_v6; then

View File

@ -32,6 +32,10 @@ iter_whitelist_packages() {
esac
# Keep first token only; ignore any inline prose if present.
# Intentional word split to grab the first token. This runs under
# /system/bin/sh on the phone, where arrays do not exist, so an
# unquoted expansion is the POSIX way to do it.
# shellcheck disable=SC2086
set -- $line
pkg="$1"
@ -157,10 +161,10 @@ cmd_status() {
echo ""
# Show current location if available
location="$(dumpsys location 2>/dev/null \
| grep -oE 'Location\[.*[-]?[0-9]{1,3}\.[0-9]+,[-]?[0-9]{1,3}\.[0-9]+' \
| grep -oE '[-]?[0-9]{1,3}\.[0-9]+,[-]?[0-9]{1,3}\.[0-9]+' \
| head -1)"
location="$(dumpsys location 2>/dev/null |
grep -oE 'Location\[.*[-]?[0-9]{1,3}\.[0-9]+,[-]?[0-9]{1,3}\.[0-9]+' |
grep -oE '[-]?[0-9]{1,3}\.[0-9]+,[-]?[0-9]{1,3}\.[0-9]+' |
head -1)"
if [ -n "$location" ]; then
lat="$(echo "$location" | cut -d',' -f1)"
@ -202,7 +206,10 @@ cmd_enable() {
for w in $(iter_whitelist_packages); do
w_clean="$(echo "$w" | tr -d '[:space:]')"
[ -z "$w_clean" ] && continue
[ "$pkg" = "$w_clean" ] && { whitelisted=1; break; }
[ "$pkg" = "$w_clean" ] && {
whitelisted=1
break
}
done
[ "$whitelisted" -eq 1 ] && continue
@ -212,7 +219,10 @@ cmd_enable() {
prefix_clean="$(echo "$prefix" | tr -d '[:space:]')"
[ -z "$prefix_clean" ] && continue
case "$pkg" in
"$prefix_clean"*) protected=1; break ;;
"$prefix_clean"*)
protected=1
break
;;
esac
done
[ "$protected" -eq 1 ] && continue
@ -285,7 +295,10 @@ cmd_list_apps() {
for w in $(iter_whitelist_packages); do
w="$(echo "$w" | tr -d '[:space:]')"
[ -z "$w" ] && continue
[ "$pkg" = "$w" ] && { whitelisted=1; break; }
[ "$pkg" = "$w" ] && {
whitelisted=1
break
}
done
if [ "$whitelisted" -eq 0 ]; then
# Check if currently disabled by focus mode
@ -563,8 +576,8 @@ cmd_launcher_snapshot() {
# Fall back to the launcher's MAIN/LAUNCHER activity
component="$(cmd package resolve-activity --brief \
-c android.intent.category.LAUNCHER \
-a android.intent.action.MAIN "$LAUNCHER_PACKAGE" 2>/dev/null \
| awk 'NR==2{print}')"
-a android.intent.action.MAIN "$LAUNCHER_PACKAGE" 2>/dev/null |
awk 'NR==2{print}')"
fi
if [ -z "$component" ]; then
echo "ERROR: could not resolve HOME activity for $LAUNCHER_PACKAGE"
@ -652,7 +665,7 @@ cmd_launcher_stop() {
if [ -s "$DISABLED_COMPETITORS_FILE" ]; then
while read -r pkg; do
[ -z "$pkg" ] && continue
pm enable --user 0 "$pkg" >/dev/null 2>&1 && \
pm enable --user 0 "$pkg" >/dev/null 2>&1 &&
echo "Re-enabled competing launcher: $pkg"
done <"$DISABLED_COMPETITORS_FILE"
: >"$DISABLED_COMPETITORS_FILE"
@ -807,7 +820,9 @@ ctl_is_curfew_now() {
local now start end
now="$(date +%H%M 2>/dev/null)"
case "$now" in '' | *[!0-9]*) return 1 ;; esac
now="$(_ctl_dec "$now")"; start="$(_ctl_dec "$NIGHT_CURFEW_START")"; end="$(_ctl_dec "$NIGHT_CURFEW_END")"
now="$(_ctl_dec "$now")"
start="$(_ctl_dec "$NIGHT_CURFEW_START")"
end="$(_ctl_dec "$NIGHT_CURFEW_END")"
if [ "$start" -le "$end" ]; then
[ "$now" -ge "$start" ] && [ "$now" -lt "$end" ]
else
@ -832,8 +847,8 @@ cmd_curfew_status() {
if [ -f "$MODE_FILE" ]; then
echo "Focus mode: $(cat "$MODE_FILE" 2>/dev/null)"
fi
[ -e "$CURFEW_ENFORCER_STATE" ] && echo "Applied now: YES (grayscale/DND locked)" \
|| echo "Applied now: no"
[ -e "$CURFEW_ENFORCER_STATE" ] && echo "Applied now: YES (grayscale/DND locked)" ||
echo "Applied now: no"
echo "Grayscale: ${CURFEW_GRAYSCALE_ENABLED} DND: ${CURFEW_DND_ENABLED} Net: ${CURFEW_NET_ENABLED}"
if iptables -L "$CURFEW_NET_IPT_CHAIN" >/dev/null 2>&1; then
echo "iptables $CURFEW_NET_IPT_CHAIN: $(iptables -S "$CURFEW_NET_IPT_CHAIN" 2>/dev/null | wc -l) rules"
@ -878,7 +893,8 @@ cmd_curfew_log() { tail -n "${1:-50}" "$CURFEW_ENFORCER_LOG" 2>/dev/null || echo
# Test hook: force curfew ACTIVE regardless of clock/location so the whole
# stack can be validated during the day. Daemon re-checks within one tick.
cmd_curfew_test_on() {
touch "$CURFEW_FORCE_FILE"; chmod 666 "$CURFEW_FORCE_FILE" 2>/dev/null || true
touch "$CURFEW_FORCE_FILE"
chmod 666 "$CURFEW_FORCE_FILE" 2>/dev/null || true
rm -f "$CURFEW_OVERRIDE_FILE"
touch "$RECHECK_TRIGGER" 2>/dev/null || true
echo "Curfew FORCED ON. App sweep + enforcer will engage within a few seconds."
@ -895,7 +911,8 @@ cmd_curfew_test_off() {
# on-demand demo. The companion app's Start/Stop demo button drives the same
# force file. Easy off: curfew-demo-off (or tap "Stop demo curfew").
cmd_curfew_demo_on() {
touch "$CURFEW_FORCE_FILE"; chmod 666 "$CURFEW_FORCE_FILE" 2>/dev/null || true
touch "$CURFEW_FORCE_FILE"
chmod 666 "$CURFEW_FORCE_FILE" 2>/dev/null || true
rm -f "$CURFEW_OVERRIDE_FILE"
touch "$RECHECK_TRIGGER" 2>/dev/null || true
echo "Demo curfew STARTED - full curfew engaged now (apps, grayscale, DND, net)."
@ -912,7 +929,8 @@ cmd_curfew_demo_off() {
# until you re-arm. Reachable on-device only via ADB (this command) unless a
# root file-manager/terminal has been added to NIGHT_WHITELIST.
cmd_curfew_off() {
touch "$CURFEW_OVERRIDE_FILE"; chmod 666 "$CURFEW_OVERRIDE_FILE" 2>/dev/null || true
touch "$CURFEW_OVERRIDE_FILE"
chmod 666 "$CURFEW_OVERRIDE_FILE" 2>/dev/null || true
touch "$RECHECK_TRIGGER" 2>/dev/null || true
echo "Curfew SUSPENDED (override set: $CURFEW_OVERRIDE_FILE). Re-arm with: curfew-on"
}
@ -953,8 +971,8 @@ cmd_tether_status() {
fi
[ -e "$TETHER_FORCE_FILE" ] && echo "Forced ON: YES (test active)"
[ -e "$TETHER_OVERRIDE_FILE" ] && echo "Override: YES (block SUSPENDED)"
[ -e "$TETHER_ENFORCER_STATE" ] && echo "Applied now: YES (offload off + FORWARD reject)" \
|| echo "Applied now: no"
[ -e "$TETHER_ENFORCER_STATE" ] && echo "Applied now: YES (offload off + FORWARD reject)" ||
echo "Applied now: no"
local off
off="$(settings get global "$TETHER_OFFLOAD_KEY" 2>/dev/null)"
echo "tether_offload_disabled: ${off:-<unset>}"
@ -1008,7 +1026,8 @@ cmd_tether_log() { tail -n "${1:-50}" "$TETHER_LOG" 2>/dev/null || echo "No teth
# Test hook: force the block ACTIVE regardless of location so the full stack can
# be validated during the day with a real second phone on the hotspot.
cmd_tether_test_on() {
touch "$TETHER_FORCE_FILE"; chmod 666 "$TETHER_FORCE_FILE" 2>/dev/null || true
touch "$TETHER_FORCE_FILE"
chmod 666 "$TETHER_FORCE_FILE" 2>/dev/null || true
rm -f "$TETHER_OVERRIDE_FILE"
echo "Tether block FORCED ON. Enforcer engages within ${TETHER_CHECK_INTERVAL}s."
echo "Validate: second phone on the hotspot loses internet; this phone stays online."
@ -1028,7 +1047,11 @@ case "$1" in
log) cmd_log "${2:-50}" ;;
list-apps) cmd_list_apps ;;
whitelist) cmd_whitelist ;;
restart) cmd_stop; sleep 2; cmd_start ;;
restart)
cmd_stop
sleep 2
cmd_start
;;
hosts-status) cmd_hosts_status ;;
hosts-start) cmd_hosts_start ;;
hosts-stop) cmd_hosts_stop ;;

View File

@ -20,7 +20,7 @@ acquire_lock() {
if kill -0 "$old_pid" 2>/dev/null; then
# Verify the PID is actually a focus_daemon, not a reused PID
local cmdline
cmdline="$(cat /proc/$old_pid/cmdline 2>/dev/null | tr '\0' ' ')"
cmdline="$(tr '\0' ' ' <"/proc/$old_pid/cmdline" 2>/dev/null)"
if echo "$cmdline" | grep -q "focus_daemon"; then
echo "Daemon already running (PID $old_pid), exiting."
exit 0
@ -52,8 +52,8 @@ rotate_log() {
# ---- Build helper files for fast package checks ----
build_whitelist_file() {
echo "$WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' \
| sed 's/^[[:space:]]*//;s/[[:space:]]*$//' > "$STATE_DIR/whitelist.txt"
echo "$WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/whitelist.txt"
# Sanity check: the WHITELIST string in config.sh is fragile - any
# literal double-quote inside a comment will close the heredoc and
# silently truncate the variable. Log the parsed line count so any
@ -70,8 +70,8 @@ build_whitelist_file() {
build_night_whitelist_file() {
# Strict allow-list used while the night curfew is active (see config.sh
# NIGHT_WHITELIST and is_curfew_now()). Parsed exactly like the day list.
echo "$NIGHT_WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' \
| sed 's/^[[:space:]]*//;s/[[:space:]]*$//' > "$STATE_DIR/night_whitelist.txt"
echo "$NIGHT_WHITELIST" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/night_whitelist.txt"
local n
n=$(wc -l <"$STATE_DIR/night_whitelist.txt" 2>/dev/null | tr -d ' ')
log "Night-curfew whitelist parsed: $n entries"
@ -81,16 +81,16 @@ build_night_whitelist_file() {
}
build_sysprotect_file() {
echo "$SYSTEM_NEVER_DISABLE" | grep -v '^[[:space:]]*$' \
| sed 's/^[[:space:]]*//;s/[[:space:]]*$//' > "$STATE_DIR/sysprotect.txt"
echo "$SYSTEM_NEVER_DISABLE" | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/sysprotect.txt"
}
# $BLOCKED_SYSTEM_APPS is a static config value (never changes without a
# daemon restart), so - like build_sysprotect_file above - this only needs
# to run once at startup, not every enable_focus_mode() sweep.
build_blocked_sys_file() {
echo "$BLOCKED_SYSTEM_APPS" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' \
| sed 's/^[[:space:]]*//;s/[[:space:]]*$//' > "$STATE_DIR/blocked_sys.txt"
echo "$BLOCKED_SYSTEM_APPS" | grep -v '^[[:space:]]*#' | grep -v '^[[:space:]]*$' |
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' >"$STATE_DIR/blocked_sys.txt"
}
reconcile_disabled_apps() {
@ -165,9 +165,9 @@ init() {
# ---- Location ----
get_location() {
dumpsys location 2>/dev/null \
| grep -oE '[-]?[0-9]{1,3}\.[0-9]{4,},[-]?[0-9]{1,3}\.[0-9]{4,}' \
| head -1
dumpsys location 2>/dev/null |
grep -oE '[-]?[0-9]{1,3}\.[0-9]{4,},[-]?[0-9]{1,3}\.[0-9]{4,}' |
head -1
}
# ---- Distance Calculation (Haversine via awk) ----
@ -209,7 +209,9 @@ is_curfew_now() {
case "$now" in
'' | *[!0-9]*) return 1 ;;
esac
now="$(_dec "$now")"; start="$(_dec "$NIGHT_CURFEW_START")"; end="$(_dec "$NIGHT_CURFEW_END")"
now="$(_dec "$now")"
start="$(_dec "$NIGHT_CURFEW_START")"
end="$(_dec "$NIGHT_CURFEW_END")"
if [ "$start" -le "$end" ]; then
[ "$now" -ge "$start" ] && [ "$now" -lt "$end" ]
else
@ -275,8 +277,8 @@ is_allowed() {
is_default_handler "$pkg" && return 0
# The default browser is guarded only OUTSIDE curfew. At night the whole
# point is to disable browsers, so this guard must not re-allow it.
if ! curfew_active \
&& grep -qxF "$pkg" "$STATE_DIR/default_browser.txt" 2>/dev/null; then
if ! curfew_active &&
grep -qxF "$pkg" "$STATE_DIR/default_browser.txt" 2>/dev/null; then
return 0
fi
return 1
@ -292,8 +294,8 @@ refresh_default_handlers() {
# Default Home (launcher). resolve-activity prints "Activity Resolver Table:"
# on line 1 and "<pkg>/<.Activity>" on line 2 in --brief mode.
cmd package resolve-activity --brief \
-c android.intent.category.HOME -a android.intent.action.MAIN 2>/dev/null \
| awk -F/ 'NR==2 && $1 != "" {print $1}' >> "$tmp"
-c android.intent.category.HOME -a android.intent.action.MAIN 2>/dev/null |
awk -F/ 'NR==2 && $1 != "" {print $1}' >>"$tmp"
# Default Dialer
local dialer
dialer="$(cmd telecom get-default-dialer 2>/dev/null | tr -d '[:space:]')"
@ -317,8 +319,8 @@ refresh_default_handlers() {
# disable browsers, so the default-handler guard must not resurrect them.
local bf="$STATE_DIR/default_browser.txt"
cmd package resolve-activity --brief \
-a android.intent.action.VIEW -d http://example.com 2>/dev/null \
| awk -F/ 'NR==2 && $1 != "" {print $1}' > "$bf.tmp" 2>/dev/null
-a android.intent.action.VIEW -d http://example.com 2>/dev/null |
awk -F/ 'NR==2 && $1 != "" {print $1}' >"$bf.tmp" 2>/dev/null
mv "$bf.tmp" "$bf" 2>/dev/null || : >"$bf"
}
@ -356,8 +358,8 @@ enable_focus_mode() {
[ -z "$pkg" ] && continue
is_allowed "$pkg" && continue
if pm disable-user --user 0 "$pkg" >/dev/null 2>&1; then
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null \
|| echo "$pkg" >> "$DISABLED_APPS_FILE"
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null ||
echo "$pkg" >>"$DISABLED_APPS_FILE"
newly_disabled=$((newly_disabled + 1))
fi
done <"$tmp_pkgs"
@ -376,8 +378,8 @@ enable_focus_mode() {
while IFS= read -r pkg; do
[ -z "$pkg" ] && continue
if pm disable-user --user 0 "$pkg" >/dev/null 2>&1; then
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null \
|| echo "$pkg" >> "$DISABLED_APPS_FILE"
grep -qxF "$pkg" "$DISABLED_APPS_FILE" 2>/dev/null ||
echo "$pkg" >>"$DISABLED_APPS_FILE"
newly_disabled=$((newly_disabled + 1))
fi
done <"$blocked_sys"
@ -516,7 +518,8 @@ main() {
disable_focus_mode
fi
curfew_state="day"; curfew_active && curfew_state="CURFEW"
curfew_state="day"
curfew_active && curfew_state="CURFEW"
log "Location: $lat,$lon | Distance: ${distance}m | Threshold: ${threshold}m | Mode: $CURRENT_MODE | Curfew: $curfew_state"
write_status_snapshot "$CURRENT_MODE" "$lat" "$lon" "$distance" "$threshold"
else

View File

@ -11,13 +11,23 @@ cd "$SCRIPT_DIR"
SDK="${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}"
# Pick highest-numbered build-tools directory.
BUILD_TOOLS_DIR="$(ls -1d "$SDK"/build-tools/*/ 2>/dev/null | sort -V | tail -1 | sed 's:/$::')"
# A glob into an array rather than parsing ls: a build-tools path containing a
# space or newline would otherwise be split into garbage.
_bt_dirs=("$SDK"/build-tools/*/)
BUILD_TOOLS_DIR="$(printf '%s\n' "${_bt_dirs[@]}" | sort -V | tail -1 | sed 's:/$::')"
# Pick highest-numbered platform.
PLATFORM_DIR="$(ls -1d "$SDK"/platforms/android-*/ 2>/dev/null | sort -V | tail -1 | sed 's:/$::')"
_plat_dirs=("$SDK"/platforms/android-*/)
PLATFORM_DIR="$(printf '%s\n' "${_plat_dirs[@]}" | sort -V | tail -1 | sed 's:/$::')"
PLATFORM_JAR="$PLATFORM_DIR/android.jar"
[ -d "$BUILD_TOOLS_DIR" ] || { echo "ERROR: build-tools not found under $SDK" >&2; exit 1; }
[ -f "$PLATFORM_JAR" ] || { echo "ERROR: android.jar not found at $PLATFORM_JAR" >&2; exit 1; }
[ -d "$BUILD_TOOLS_DIR" ] || {
echo "ERROR: build-tools not found under $SDK" >&2
exit 1
}
[ -f "$PLATFORM_JAR" ] || {
echo "ERROR: android.jar not found at $PLATFORM_JAR" >&2
exit 1
}
AAPT2="$BUILD_TOOLS_DIR/aapt2"
D8="$BUILD_TOOLS_DIR/d8"
@ -25,7 +35,10 @@ ZIPALIGN="$BUILD_TOOLS_DIR/zipalign"
APKSIGNER="$BUILD_TOOLS_DIR/apksigner"
for tool in "$AAPT2" "$D8" "$ZIPALIGN" "$APKSIGNER"; do
[ -x "$tool" ] || { echo "ERROR: missing build tool: $tool" >&2; exit 1; }
[ -x "$tool" ] || {
echo "ERROR: missing build tool: $tool" >&2
exit 1
}
done
BUILD="$SCRIPT_DIR/build"

View File

@ -25,6 +25,10 @@ mkdir -p "${XDG_STATE_HOME}"
source "${SCRIPT_DIR}/../adb_common.sh"
ADB_MOCK_MODEL=$'Pixel "7";$(rm -rf /)`danger`\nline2'
# Single quotes are the whole point: this is an injection payload that must
# reach the code under test LITERALLY. Expanding $evil / `cmd` here would
# execute them in the test harness and test nothing.
# shellcheck disable=SC2016
ADB_MOCK_FINGERPRINT='google/pixel:14/UP1A.231005.007/$evil;`cmd`'
adb() {
@ -121,12 +125,17 @@ test_sanitize_device_string_removes_dangerous_chars() {
test_save_trusted_device_sanitizes_and_quotes() {
local trusted_contents
# Literal payload on purpose - see the note on ADB_MOCK_FINGERPRINT.
# shellcheck disable=SC2016
export ADB_SERIAL='SERIAL123$() ;'
adb_save_trusted_device
[[ -f "${TRUSTED_DEVICE_FILE}" ]] || return 1
trusted_contents="$(cat "${TRUSTED_DEVICE_FILE}")"
# Asserting the sanitiser stripped these metacharacters, so the patterns
# must stay literal rather than expand.
# shellcheck disable=SC2016
[[ "${trusted_contents}" != *'$('* ]]
[[ "${trusted_contents}" != *';'* ]]
[[ "${trusted_contents}" != *'`'* ]]

View File

@ -75,9 +75,16 @@ printf '#!/usr/bin/env bash\necho 13\n' > "$RUN/bin/getprop"
chmod +x "$RUN/bin/"*
export PATH="$RUN/bin:$PATH"
PASS=0; FAIL=0
ok() { PASS=$((PASS + 1)); printf ' OK: %s\n' "$1"; }
no() { FAIL=$((FAIL + 1)); printf ' FAIL: %s\n' "$1"; }
PASS=0
FAIL=0
ok() {
PASS=$((PASS + 1))
printf ' OK: %s\n' "$1"
}
no() {
FAIL=$((FAIL + 1))
printf ' FAIL: %s\n' "$1"
}
applied() { [ -f "$STATE/tether_applied" ]; }
offload() { cat "$RUN/settings/tether_offload_disabled" 2>/dev/null || echo "<unset>"; }
v4jump() { [ -f "$RUN/ipt/iptables/jump" ]; }
@ -85,39 +92,44 @@ v6jump() { [ -f "$RUN/ipt/ip6tables/jump" ]; }
v4rules() { grep -c '^-A' "$RUN/ipt/iptables/rules" 2>/dev/null || echo 0; }
softap() { grep -c 'stop-softap' "$RUN/calls/cmd.log" 2>/dev/null || echo 0; }
sh "$RUN/app/tether_enforcer.sh" & PID=$!
sh "$RUN/app/tether_enforcer.sh" &
PID=$!
sleep 2
# [A] Away from home -> block OFF
applied && no "A: applied while away" || ok "A: not applied while away"
[ "$(offload)" = "<unset>" ] && ok "A: offload untouched away" || no "A: offload changed away"
v4jump && no "A: v4 jump while away" || ok "A: no v4 jump while away"
if applied; then no "A: applied while away"; else ok "A: not applied while away"; fi
if [ "$(offload)" = "<unset>" ]; then ok "A: offload untouched away"; else no "A: offload changed away"; fi
if v4jump; then no "A: v4 jump while away"; else ok "A: no v4 jump while away"; fi
# [B] force-on -> block ENGAGES (all three levers)
touch "$STATE/tether_force_on"; sleep 3
applied && ok "B: applied on force" || no "B: not applied on force"
[ "$(offload)" = "1" ] && ok "B: offload disabled" || no "B: offload=$(offload)"
v4jump && ok "B: v4 FORWARD jump pinned" || no "B: no v4 jump"
v6jump && ok "B: v6 FORWARD jump pinned" || no "B: no v6 jump"
[ "$(v4rules)" = "1" ] && ok "B: single REJECT rule (no rebuild loop)" || no "B: v4 rules=$(v4rules)"
[ "$(softap)" -ge 1 ] && ok "B: stop-softap invoked" || no "B: softap not stopped"
[ "$(cat "$STATE/tether_offload.snap" 2>/dev/null)" = "null" ] && ok "B: offload snapshot captured" || no "B: bad snapshot"
touch "$STATE/tether_force_on"
sleep 3
if applied; then ok "B: applied on force"; else no "B: not applied on force"; fi
if [ "$(offload)" = "1" ]; then ok "B: offload disabled"; else no "B: offload=$(offload)"; fi
if v4jump; then ok "B: v4 FORWARD jump pinned"; else no "B: no v4 jump"; fi
if v6jump; then ok "B: v6 FORWARD jump pinned"; else no "B: no v6 jump"; fi
if [ "$(v4rules)" = "1" ]; then ok "B: single REJECT rule (no rebuild loop)"; else no "B: v4 rules=$(v4rules)"; fi
if [ "$(softap)" -ge 1 ]; then ok "B: stop-softap invoked"; else no "B: softap not stopped"; fi
if [ "$(cat "$STATE/tether_offload.snap" 2>/dev/null)" = "null" ]; then ok "B: offload snapshot captured"; else no "B: bad snapshot"; fi
# [C] clear force -> block REVERTS
rm -f "$STATE/tether_force_on"; sleep 3
applied && no "C: still applied" || ok "C: reverted on force-clear"
[ "$(offload)" = "<unset>" ] && ok "C: offload restored" || no "C: offload=$(offload)"
v4jump && no "C: v4 jump remains" || ok "C: v4 chain torn down"
rm -f "$STATE/tether_force_on"
sleep 3
if applied; then no "C: still applied"; else ok "C: reverted on force-clear"; fi
if [ "$(offload)" = "<unset>" ]; then ok "C: offload restored"; else no "C: offload=$(offload)"; fi
if v4jump; then no "C: v4 jump remains"; else ok "C: v4 chain torn down"; fi
# [D] current_mode=focus -> ENGAGES via home gate
echo focus > "$STATE/current_mode.txt"; sleep 3
applied && ok "D: applied at home (focus)" || no "D: not applied at home"
v4jump && ok "D: v4 jump pinned at home" || no "D: no v4 jump at home"
echo focus >"$STATE/current_mode.txt"
sleep 3
if applied; then ok "D: applied at home (focus)"; else no "D: not applied at home"; fi
if v4jump; then ok "D: v4 jump pinned at home"; else no "D: no v4 jump at home"; fi
# [E] override -> SUSPENDS even at home
touch "$STATE/tether_override"; sleep 3
applied && no "E: applied despite override" || ok "E: suspended by override"
v4jump && no "E: v4 jump despite override" || ok "E: torn down by override"
touch "$STATE/tether_override"
sleep 3
if applied; then no "E: applied despite override"; else ok "E: suspended by override"; fi
if v4jump; then no "E: v4 jump despite override"; else ok "E: torn down by override"; fi
printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]