mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 12:06:17 +01:00
Compare commits
4 Commits
0aa78ea7aa
...
82d0eb91f1
| Author | SHA1 | Date | |
|---|---|---|---|
| 82d0eb91f1 | |||
| 093e2f6f68 | |||
| 45b56b3e61 | |||
| 5387c5d19d |
@ -151,6 +151,19 @@ emitting three files.
|
||||
records why `settings.yml` is mode 640 and not 600 (at 600 the granian worker
|
||||
dies with EACCES) — that comment is worth more than the code around it.
|
||||
|
||||
### A seam inside a heredoc produces a file that will not parse
|
||||
|
||||
The worst failure in this effort: the split of `enforce_vbox_hosts.sh` cut
|
||||
between `cat <<EOF` and its terminator, leaving a lib with an unterminated
|
||||
here-document. `shellcheck` on the **entry** reported only SC1094 "parsing of
|
||||
sourced file failed", which reads like a linting nicety rather than a broken
|
||||
file, and the entry itself still linted clean with `-x`.
|
||||
|
||||
`meta/scripts/verify_shell_split.sh` now runs `bash -n` over every lib
|
||||
**before** linting the entry and names the offending file. The splitter is
|
||||
still heredoc-unaware, so check for `<<` in the region you are moving before
|
||||
choosing a boundary.
|
||||
|
||||
### When to give up on a seam
|
||||
|
||||
`clean_audio.sh` was reverted. Two probe-result globals were read by functions
|
||||
|
||||
@ -0,0 +1,18 @@
|
||||
{
|
||||
"title": "Split raspberry_pi_flash_sd.sh and test_boot_repair.sh under the cap",
|
||||
"objective": "Bring raspberry_pi_flash_sd.sh (661) and test_boot_repair.sh (315) under the 250-line cap, choosing seams that avoid heredocs after the enforce_vbox_hosts failure.",
|
||||
"acceptance_criteria": [
|
||||
"Both entry scripts and all four new libs are at most 250 lines.",
|
||||
"The pre-commit shellcheck hook passes on every touched file, with no new suppression and no disable directive.",
|
||||
"No lib sources a sibling; every lib parses under bash -n.",
|
||||
"Every seam is chosen outside a heredoc: the heredoc line numbers are listed before picking cut points.",
|
||||
"test_boot_repair.sh is a sandboxed fixture harness, so it MUST be run: it has to report the same pass count after the split as a clean worktree at HEAD reports before it.",
|
||||
"raspberry_pi_flash_sd.sh is not executed - it writes partition tables to an SD card."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Executing raspberry_pi_flash_sd.sh or any flashing step.",
|
||||
"The seven deferred shell scripts.",
|
||||
"Changing what any script does when run."
|
||||
],
|
||||
"verifier": "meta/scripts/verify_shell_split.sh for both, plus running test_boot_repair.sh and comparing its pass count against the same script run from a detached worktree at HEAD, plus pre-commit run --files and check_file_length.sh."
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
{
|
||||
"title": "Split the reverse_survivors test files under the 250-line cap",
|
||||
"objective": "Bring sim.test.ts (698) and director.test.ts (315) under the cap by partitioning at describe boundaries, and establish that its two core source files cannot be split without breaking a runtime dependency.",
|
||||
"acceptance_criteria": [
|
||||
"No reverse_survivors test file is over 250 lines.",
|
||||
"The suite still reports exactly 160 passing tests.",
|
||||
"npx tsc --noEmit and npx eslint . --max-warnings 0 both pass, with no new suppression.",
|
||||
"No test is deleted, skipped or weakened; whole describe blocks move verbatim.",
|
||||
"sim.ts and types.ts are fully restored, leaving no partial split and no orphan module."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"sim.ts, whose exported step() calls survivorStep and the enemy helpers that any seam would move.",
|
||||
"types.ts, whose difficulty tables are referenced by the type declarations above them.",
|
||||
"Changing what any test asserts."
|
||||
],
|
||||
"verifier": "npm test -- --run (expects exactly 160 passed), npx tsc --noEmit, npx eslint . --max-warnings 0, and check_file_length.sh over reverse_survivors."
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
{
|
||||
"intent": "Split two more linux_configuration scripts, one of which could finally be verified by actually running it.",
|
||||
"scope": [
|
||||
"single_use/features/raspberry_pi_flash_sd.sh (661 -> 166) + pi_flash_remote, pi_flash_image, pi_flash_exec",
|
||||
"boot_recovery/tests/test_boot_repair.sh (315 -> 104) + boot_repair_cases.sh",
|
||||
"Non-goal: raspberry_pi_flash_sd.sh not executed"
|
||||
],
|
||||
"changes": [
|
||||
"Both scripts were checked for heredoc positions BEFORE choosing seams, after the enforce_vbox_hosts split cut inside one. raspberry_pi_flash_sd.sh has heredocs at lines 68 and 609; the three cut points (134, 273, 460) sit clear of both.",
|
||||
"test_boot_repair.sh's fixtures and repair cases moved to boot_repair_cases.sh, leaving the assertions and the runner in the entry."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "bash linux_configuration/scripts/boot_recovery/tests/test_boot_repair.sh",
|
||||
"result": "pass",
|
||||
"evidence": "31 passed, 0 failed. This is the first linux_configuration script in the whole effort that could be RUN as verification rather than statically checked: its header documents that every case builds a throwaway root in a temp dir and passes --root, so nothing on the machine is touched."
|
||||
},
|
||||
{
|
||||
"command": "same script from a detached worktree at HEAD",
|
||||
"result": "pass",
|
||||
"evidence": "31 passed, 0 failed - the identical count, so the split neither lost nor duplicated a case. Establishing the baseline from a clean worktree rather than trusting the post-split number is the shell equivalent of the pass-count rule used throughout python_pkg."
|
||||
},
|
||||
{
|
||||
"command": "meta/scripts/verify_shell_split.sh for both scripts",
|
||||
"result": "pass",
|
||||
"evidence": "Both report 'libs sourced, functions defined' on the first attempt - no chained libs, no SCRIPT_DIR collision, no heredoc cut."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <6 changed files>",
|
||||
"result": "pass",
|
||||
"evidence": "Clean, including shellcheck over each lib in isolation."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"raspberry_pi_flash_sd.sh writes partition tables to an SD card and was not run; only the stubbed run and the static checks cover it.",
|
||||
"Checking heredoc positions before choosing a seam is currently a manual step. The verifier catches the failure afterwards via bash -n, but the splitter still has no heredoc awareness."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; both scripts return to 661 and 315 lines and the four libs disappear.",
|
||||
"After rollback, re-run test_boot_repair.sh and expect 31 passed."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
{
|
||||
"intent": "Clear the reverse_survivors test files under the cap, and defer its two core source files after both seams failed.",
|
||||
"scope": [
|
||||
"src/core/sim.test.ts (698 -> 175) + simEnemies, simUnits, simFrenzy test modules",
|
||||
"src/core/director.test.ts (315 -> 178) + directorPowers.test.ts",
|
||||
"Reverted: src/core/sim.ts (361), src/core/types.ts (295)",
|
||||
"Non-goal: no assertion changed, no test deleted"
|
||||
],
|
||||
"changes": [
|
||||
"Four new test modules, each carrying the original preamble; the unused imports and orphaned local helpers were then pruned iteratively from tsc's own TS6133/TS6192/TS6196 output rather than guessed.",
|
||||
"sim.ts was reverted: its exported step() calls survivorStep, which any seam moves out, so the suite failed with 'ReferenceError: survivorStep is not defined' in 63 tests. tsc reported only unused-import warnings on that same code.",
|
||||
"types.ts was reverted: the difficulty tables sit below type declarations that reference them, so moving them left StatusKind, EnemyKind and BossKind unresolvable in the new module."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "npm test -- --run",
|
||||
"result": "fail twice, then pass",
|
||||
"evidence": "160 passed in 13 files, matching the baseline of 160. The two failures were the source splits, not the test splits: 63 and then 64 tests failed with a ReferenceError, which is again a runtime-only symptom that tsc did not catch."
|
||||
},
|
||||
{
|
||||
"command": "npx tsc --noEmit && npx eslint . --max-warnings 0",
|
||||
"result": "pass",
|
||||
"evidence": "Both clean after pruning roughly a dozen imports and two orphaned test helpers."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep reverse",
|
||||
"result": "pass",
|
||||
"evidence": "Only sim.ts and types.ts remain, both source files, both deliberately deferred."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"This is the third project where a TypeScript seam compiled clean and failed at runtime. The pattern is consistent enough to state plainly: in TS, tsc is not a check that a split worked - only the test run is.",
|
||||
"sim.ts and types.ts stay over the cap. Splitting sim.ts means passing the step functions in or hoisting them into a third module; types.ts needs its type declarations separated from the tables that use them."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the two originals return at 698 and 315 lines and the four new modules disappear.",
|
||||
"After rollback, re-run npm test and expect 160 passed."
|
||||
]
|
||||
}
|
||||
221
linux_configuration/scripts/boot_recovery/tests/lib/boot_repair_cases.sh
Executable file
221
linux_configuration/scripts/boot_recovery/tests/lib/boot_repair_cases.sh
Executable file
@ -0,0 +1,221 @@
|
||||
#!/bin/bash
|
||||
# Test fixtures and the individual repair cases.
|
||||
#
|
||||
# Sourced by test_boot_repair.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Fixture construction
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# make_root <name> -> prints the path to a fresh fixture root
|
||||
#
|
||||
# Builds a consistent system: one complete kernel tree, an ESP whose kernel
|
||||
# and initramfs match it, a gating fstab and serial downloads.
|
||||
make_root() {
|
||||
local name="$1"
|
||||
local r="$WORKROOT/$name"
|
||||
local kver="${2:-7.1.5-arch1-2}"
|
||||
|
||||
mkdir -p "$r/usr/lib/modules/$kver/kernel/fs/fat"
|
||||
mkdir -p "$r/boot" "$r/etc" "$r/var/cache/pacman/pkg"
|
||||
|
||||
# Fake kernel image carrying the version banner boot-repair greps for.
|
||||
printf 'Linux version %s (linux@archlinux) fake image\n' "$kver" \
|
||||
>"$r/usr/lib/modules/$kver/vmlinuz"
|
||||
: >"$r/usr/lib/modules/$kver/modules.dep"
|
||||
: >"$r/usr/lib/modules/$kver/kernel/fs/fat/vfat.ko.zst"
|
||||
|
||||
# ESP contents, consistent with the kernel tree.
|
||||
cp "$r/usr/lib/modules/$kver/vmlinuz" "$r/boot/vmlinuz-linux"
|
||||
printf 'usr/lib/modules/%s/kernel/fs/fat/vfat.ko.zst\n' "$kver" \
|
||||
>"$r/boot/initramfs-linux.img"
|
||||
mkdir -p "$r/boot/EFI" "$r/boot/loader"
|
||||
|
||||
printf 'UUID=DEAD-BEEF\t/boot\tvfat\tdefaults\t0 2\n' >"$r/etc/fstab"
|
||||
printf 'ParallelDownloads = 1\n' >"$r/etc/pacman.conf"
|
||||
|
||||
printf '%s' "$r"
|
||||
}
|
||||
|
||||
run_repair() {
|
||||
"$BOOT_REPAIR" --root "$1" "${@:2}" 2>&1
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
test_healthy_system() {
|
||||
echo "TEST: healthy system reports consistent"
|
||||
local r out rc
|
||||
r="$(make_root healthy)"
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
rc=$?
|
||||
assert_eq "exit status is 0" "$rc" "0"
|
||||
assert_contains "reports consistent" "$out" "nothing to repair"
|
||||
assert_contains "picks the right kernel" "$out" "target kernel: 7.1.5-arch1-2"
|
||||
}
|
||||
|
||||
test_stale_esp_kernel_detected() {
|
||||
echo "TEST: stale ESP kernel is detected and repaired"
|
||||
local r out rc
|
||||
r="$(make_root stale)"
|
||||
# Simulate the real incident: ESP still holds the previous kernel.
|
||||
printf 'Linux version 7.0.5-arch1-1 (linux@archlinux) fake image\n' \
|
||||
>"$r/boot/vmlinuz-linux"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
rc=$?
|
||||
assert_eq "dry-run exits 1" "$rc" "1"
|
||||
assert_contains "detects the mismatch" "$out" "ESP kernel is 7.0.5-arch1-1 but installed tree is 7.1.5-arch1-2"
|
||||
assert_contains "dry-run changes nothing" "$out" "would install"
|
||||
|
||||
# The ESP must be untouched by a dry run.
|
||||
assert_contains "dry-run left ESP alone" "$(cat "$r/boot/vmlinuz-linux")" "7.0.5-arch1-1"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "repairs the kernel image" "$out" "installed kernel 7.1.5-arch1-2 to the ESP"
|
||||
assert_contains "ESP now has the new kernel" "$(cat "$r/boot/vmlinuz-linux")" "7.1.5-arch1-2"
|
||||
}
|
||||
|
||||
test_incomplete_tree_ignored() {
|
||||
echo "TEST: a gutted module tree is not chosen as the target"
|
||||
local r out
|
||||
r="$(make_root gutted)"
|
||||
# The exact wreckage the failed upgrade leaves: metadata only, no kernel/,
|
||||
# no vmlinuz. It sorts newer, so a naive 'newest' pick would take it.
|
||||
mkdir -p "$r/usr/lib/modules/9.9.9-arch1-1"
|
||||
: >"$r/usr/lib/modules/9.9.9-arch1-1/modules.dep"
|
||||
: >"$r/usr/lib/modules/9.9.9-arch1-1/modules.alias"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "ignores the incomplete tree" "$out" "target kernel: 7.1.5-arch1-2"
|
||||
assert_not_contains "does not pick 9.9.9" "$out" "target kernel: 9.9.9-arch1-1"
|
||||
}
|
||||
|
||||
test_picks_newest_complete() {
|
||||
echo "TEST: newest COMPLETE tree wins"
|
||||
local r out kver
|
||||
r="$(make_root multi)"
|
||||
kver="7.2.0-arch1-1"
|
||||
mkdir -p "$r/usr/lib/modules/$kver/kernel/fs/fat"
|
||||
printf 'Linux version %s (linux@archlinux) fake image\n' "$kver" \
|
||||
>"$r/usr/lib/modules/$kver/vmlinuz"
|
||||
: >"$r/usr/lib/modules/$kver/modules.dep"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "selects the newer complete tree" "$out" "target kernel: 7.2.0-arch1-1"
|
||||
}
|
||||
|
||||
test_fstab_nofail_fixed() {
|
||||
echo "TEST: noauto/nofail on /boot is detected and reset"
|
||||
local r out
|
||||
r="$(make_root fstab)"
|
||||
printf 'UUID=DEAD-BEEF\t/boot\tvfat\tdefaults,noauto,nofail\t0 2\n' >"$r/etc/fstab"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "detects the silent-failure options" "$out" "noauto/nofail"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "resets the options" "$out" "reset to 'defaults'"
|
||||
assert_contains "fstab now gates" "$(cat "$r/etc/fstab")" "defaults"
|
||||
assert_not_contains "nofail is gone" "$(cat "$r/etc/fstab")" "nofail"
|
||||
# A backup must exist so the change is reversible.
|
||||
if compgen -G "$r/etc/fstab.bak-*" >/dev/null; then
|
||||
pass "fstab backup written"
|
||||
else
|
||||
fail "fstab backup written"
|
||||
fi
|
||||
}
|
||||
|
||||
test_shadow_files_removed() {
|
||||
echo "TEST: shadow kernel files in an unmounted /boot are removed"
|
||||
local r out
|
||||
r="$(make_root shadow)"
|
||||
# An unmounted /boot has no EFI/ or loader/ — that is what makes the files
|
||||
# below shadows on the root filesystem rather than the real ESP.
|
||||
rm -rf "${r:?}/boot"
|
||||
mkdir -p "$r/boot"
|
||||
printf 'Linux version 7.1.5-arch1-2 (linux@archlinux) fake\n' >"$r/boot/vmlinuz-linux"
|
||||
printf 'usr/lib/modules/7.1.5-arch1-2/x\n' >"$r/boot/initramfs-linux.img"
|
||||
printf 'stale\n' >"$r/boot/initramfs-linux-fallback.img"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "detects the shadows" "$out" "orphaned kernel file"
|
||||
assert_contains "removes them" "$out" "removed 3 shadow file"
|
||||
# The fallback image is not regenerated by a --root run, so its absence
|
||||
# proves the deletion happened. (vmlinuz-linux legitimately reappears:
|
||||
# sync_kernel_image reinstalls the target kernel straight afterwards.)
|
||||
if [[ ! -f $r/boot/initramfs-linux-fallback.img ]]; then
|
||||
pass "shadow fallback image deleted"
|
||||
else
|
||||
fail "shadow fallback image deleted"
|
||||
fi
|
||||
}
|
||||
|
||||
test_shadow_guard_refuses_real_esp() {
|
||||
echo "TEST: SAFETY — never delete from a directory that looks like a real ESP"
|
||||
local r out
|
||||
r="$(make_root guarded)"
|
||||
# EFI/ and loader/ are present (make_root creates them), so even though the
|
||||
# fixture is "unmounted", boot-repair must refuse to delete anything.
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "refuses to delete" "$out" "refusing to delete anything"
|
||||
if [[ -f $r/boot/vmlinuz-linux ]]; then
|
||||
pass "real ESP kernel preserved"
|
||||
else
|
||||
fail "real ESP kernel preserved" "boot-repair deleted a real ESP kernel!"
|
||||
fi
|
||||
}
|
||||
|
||||
test_parallel_downloads_fixed() {
|
||||
echo "TEST: ParallelDownloads > 1 is detected and set to 1"
|
||||
local r out
|
||||
r="$(make_root paralleldl)"
|
||||
printf 'ParallelDownloads = 5\n' >"$r/etc/pacman.conf"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "detects the hook-segfault trigger" "$out" "ParallelDownloads = 5"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "sets it to 1" "$out" "set ParallelDownloads = 1"
|
||||
assert_contains "config updated" "$(cat "$r/etc/pacman.conf")" "ParallelDownloads = 1"
|
||||
}
|
||||
|
||||
test_missing_modules_dep() {
|
||||
echo "TEST: missing modules.dep is reported"
|
||||
local r out
|
||||
r="$(make_root nodep)"
|
||||
rm -f "$r/usr/lib/modules/7.1.5-arch1-2/modules.dep"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "detects missing modules.dep" "$out" "modules.dep missing for 7.1.5-arch1-2"
|
||||
}
|
||||
|
||||
test_no_kernel_at_all() {
|
||||
echo "TEST: no complete kernel tree gives actionable offline guidance"
|
||||
local r out rc
|
||||
r="$(make_root nokernel)"
|
||||
rm -rf "$r/usr/lib/modules"
|
||||
mkdir -p "$r/usr/lib/modules"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
rc=$?
|
||||
assert_eq "exits non-zero" "$rc" "1"
|
||||
assert_contains "explains the offline recovery" "$out" "pacman -U /var/cache/pacman/pkg/linux-"
|
||||
}
|
||||
|
||||
test_help_and_bad_args() {
|
||||
echo "TEST: CLI contract"
|
||||
local out rc
|
||||
out="$("$BOOT_REPAIR" --help 2>&1)"
|
||||
rc=$?
|
||||
assert_eq "--help exits 0" "$rc" "0"
|
||||
assert_contains "help mentions dry-run" "$out" "--dry-run"
|
||||
|
||||
out="$("$BOOT_REPAIR" --nonsense 2>&1)"
|
||||
rc=$?
|
||||
assert_eq "unknown option exits 2" "$rc" "2"
|
||||
}
|
||||
@ -62,220 +62,9 @@ assert_eq() {
|
||||
fi
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Fixture construction
|
||||
# ----------------------------------------------------------------------------
|
||||
# shellcheck source=lib/boot_repair_cases.sh
|
||||
source "$SCRIPT_DIR/lib/boot_repair_cases.sh"
|
||||
|
||||
# make_root <name> -> prints the path to a fresh fixture root
|
||||
#
|
||||
# Builds a consistent system: one complete kernel tree, an ESP whose kernel
|
||||
# and initramfs match it, a gating fstab and serial downloads.
|
||||
make_root() {
|
||||
local name="$1"
|
||||
local r="$WORKROOT/$name"
|
||||
local kver="${2:-7.1.5-arch1-2}"
|
||||
|
||||
mkdir -p "$r/usr/lib/modules/$kver/kernel/fs/fat"
|
||||
mkdir -p "$r/boot" "$r/etc" "$r/var/cache/pacman/pkg"
|
||||
|
||||
# Fake kernel image carrying the version banner boot-repair greps for.
|
||||
printf 'Linux version %s (linux@archlinux) fake image\n' "$kver" \
|
||||
>"$r/usr/lib/modules/$kver/vmlinuz"
|
||||
: >"$r/usr/lib/modules/$kver/modules.dep"
|
||||
: >"$r/usr/lib/modules/$kver/kernel/fs/fat/vfat.ko.zst"
|
||||
|
||||
# ESP contents, consistent with the kernel tree.
|
||||
cp "$r/usr/lib/modules/$kver/vmlinuz" "$r/boot/vmlinuz-linux"
|
||||
printf 'usr/lib/modules/%s/kernel/fs/fat/vfat.ko.zst\n' "$kver" \
|
||||
>"$r/boot/initramfs-linux.img"
|
||||
mkdir -p "$r/boot/EFI" "$r/boot/loader"
|
||||
|
||||
printf 'UUID=DEAD-BEEF\t/boot\tvfat\tdefaults\t0 2\n' >"$r/etc/fstab"
|
||||
printf 'ParallelDownloads = 1\n' >"$r/etc/pacman.conf"
|
||||
|
||||
printf '%s' "$r"
|
||||
}
|
||||
|
||||
run_repair() {
|
||||
"$BOOT_REPAIR" --root "$1" "${@:2}" 2>&1
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
test_healthy_system() {
|
||||
echo "TEST: healthy system reports consistent"
|
||||
local r out rc
|
||||
r="$(make_root healthy)"
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
rc=$?
|
||||
assert_eq "exit status is 0" "$rc" "0"
|
||||
assert_contains "reports consistent" "$out" "nothing to repair"
|
||||
assert_contains "picks the right kernel" "$out" "target kernel: 7.1.5-arch1-2"
|
||||
}
|
||||
|
||||
test_stale_esp_kernel_detected() {
|
||||
echo "TEST: stale ESP kernel is detected and repaired"
|
||||
local r out rc
|
||||
r="$(make_root stale)"
|
||||
# Simulate the real incident: ESP still holds the previous kernel.
|
||||
printf 'Linux version 7.0.5-arch1-1 (linux@archlinux) fake image\n' \
|
||||
>"$r/boot/vmlinuz-linux"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
rc=$?
|
||||
assert_eq "dry-run exits 1" "$rc" "1"
|
||||
assert_contains "detects the mismatch" "$out" "ESP kernel is 7.0.5-arch1-1 but installed tree is 7.1.5-arch1-2"
|
||||
assert_contains "dry-run changes nothing" "$out" "would install"
|
||||
|
||||
# The ESP must be untouched by a dry run.
|
||||
assert_contains "dry-run left ESP alone" "$(cat "$r/boot/vmlinuz-linux")" "7.0.5-arch1-1"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "repairs the kernel image" "$out" "installed kernel 7.1.5-arch1-2 to the ESP"
|
||||
assert_contains "ESP now has the new kernel" "$(cat "$r/boot/vmlinuz-linux")" "7.1.5-arch1-2"
|
||||
}
|
||||
|
||||
test_incomplete_tree_ignored() {
|
||||
echo "TEST: a gutted module tree is not chosen as the target"
|
||||
local r out
|
||||
r="$(make_root gutted)"
|
||||
# The exact wreckage the failed upgrade leaves: metadata only, no kernel/,
|
||||
# no vmlinuz. It sorts newer, so a naive 'newest' pick would take it.
|
||||
mkdir -p "$r/usr/lib/modules/9.9.9-arch1-1"
|
||||
: >"$r/usr/lib/modules/9.9.9-arch1-1/modules.dep"
|
||||
: >"$r/usr/lib/modules/9.9.9-arch1-1/modules.alias"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "ignores the incomplete tree" "$out" "target kernel: 7.1.5-arch1-2"
|
||||
assert_not_contains "does not pick 9.9.9" "$out" "target kernel: 9.9.9-arch1-1"
|
||||
}
|
||||
|
||||
test_picks_newest_complete() {
|
||||
echo "TEST: newest COMPLETE tree wins"
|
||||
local r out kver
|
||||
r="$(make_root multi)"
|
||||
kver="7.2.0-arch1-1"
|
||||
mkdir -p "$r/usr/lib/modules/$kver/kernel/fs/fat"
|
||||
printf 'Linux version %s (linux@archlinux) fake image\n' "$kver" \
|
||||
>"$r/usr/lib/modules/$kver/vmlinuz"
|
||||
: >"$r/usr/lib/modules/$kver/modules.dep"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "selects the newer complete tree" "$out" "target kernel: 7.2.0-arch1-1"
|
||||
}
|
||||
|
||||
test_fstab_nofail_fixed() {
|
||||
echo "TEST: noauto/nofail on /boot is detected and reset"
|
||||
local r out
|
||||
r="$(make_root fstab)"
|
||||
printf 'UUID=DEAD-BEEF\t/boot\tvfat\tdefaults,noauto,nofail\t0 2\n' >"$r/etc/fstab"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "detects the silent-failure options" "$out" "noauto/nofail"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "resets the options" "$out" "reset to 'defaults'"
|
||||
assert_contains "fstab now gates" "$(cat "$r/etc/fstab")" "defaults"
|
||||
assert_not_contains "nofail is gone" "$(cat "$r/etc/fstab")" "nofail"
|
||||
# A backup must exist so the change is reversible.
|
||||
if compgen -G "$r/etc/fstab.bak-*" >/dev/null; then
|
||||
pass "fstab backup written"
|
||||
else
|
||||
fail "fstab backup written"
|
||||
fi
|
||||
}
|
||||
|
||||
test_shadow_files_removed() {
|
||||
echo "TEST: shadow kernel files in an unmounted /boot are removed"
|
||||
local r out
|
||||
r="$(make_root shadow)"
|
||||
# An unmounted /boot has no EFI/ or loader/ — that is what makes the files
|
||||
# below shadows on the root filesystem rather than the real ESP.
|
||||
rm -rf "${r:?}/boot"
|
||||
mkdir -p "$r/boot"
|
||||
printf 'Linux version 7.1.5-arch1-2 (linux@archlinux) fake\n' >"$r/boot/vmlinuz-linux"
|
||||
printf 'usr/lib/modules/7.1.5-arch1-2/x\n' >"$r/boot/initramfs-linux.img"
|
||||
printf 'stale\n' >"$r/boot/initramfs-linux-fallback.img"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "detects the shadows" "$out" "orphaned kernel file"
|
||||
assert_contains "removes them" "$out" "removed 3 shadow file"
|
||||
# The fallback image is not regenerated by a --root run, so its absence
|
||||
# proves the deletion happened. (vmlinuz-linux legitimately reappears:
|
||||
# sync_kernel_image reinstalls the target kernel straight afterwards.)
|
||||
if [[ ! -f $r/boot/initramfs-linux-fallback.img ]]; then
|
||||
pass "shadow fallback image deleted"
|
||||
else
|
||||
fail "shadow fallback image deleted"
|
||||
fi
|
||||
}
|
||||
|
||||
test_shadow_guard_refuses_real_esp() {
|
||||
echo "TEST: SAFETY — never delete from a directory that looks like a real ESP"
|
||||
local r out
|
||||
r="$(make_root guarded)"
|
||||
# EFI/ and loader/ are present (make_root creates them), so even though the
|
||||
# fixture is "unmounted", boot-repair must refuse to delete anything.
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "refuses to delete" "$out" "refusing to delete anything"
|
||||
if [[ -f $r/boot/vmlinuz-linux ]]; then
|
||||
pass "real ESP kernel preserved"
|
||||
else
|
||||
fail "real ESP kernel preserved" "boot-repair deleted a real ESP kernel!"
|
||||
fi
|
||||
}
|
||||
|
||||
test_parallel_downloads_fixed() {
|
||||
echo "TEST: ParallelDownloads > 1 is detected and set to 1"
|
||||
local r out
|
||||
r="$(make_root paralleldl)"
|
||||
printf 'ParallelDownloads = 5\n' >"$r/etc/pacman.conf"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "detects the hook-segfault trigger" "$out" "ParallelDownloads = 5"
|
||||
|
||||
out="$(run_repair "$r")"
|
||||
assert_contains "sets it to 1" "$out" "set ParallelDownloads = 1"
|
||||
assert_contains "config updated" "$(cat "$r/etc/pacman.conf")" "ParallelDownloads = 1"
|
||||
}
|
||||
|
||||
test_missing_modules_dep() {
|
||||
echo "TEST: missing modules.dep is reported"
|
||||
local r out
|
||||
r="$(make_root nodep)"
|
||||
rm -f "$r/usr/lib/modules/7.1.5-arch1-2/modules.dep"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
assert_contains "detects missing modules.dep" "$out" "modules.dep missing for 7.1.5-arch1-2"
|
||||
}
|
||||
|
||||
test_no_kernel_at_all() {
|
||||
echo "TEST: no complete kernel tree gives actionable offline guidance"
|
||||
local r out rc
|
||||
r="$(make_root nokernel)"
|
||||
rm -rf "$r/usr/lib/modules"
|
||||
mkdir -p "$r/usr/lib/modules"
|
||||
|
||||
out="$(run_repair "$r" --dry-run)"
|
||||
rc=$?
|
||||
assert_eq "exits non-zero" "$rc" "1"
|
||||
assert_contains "explains the offline recovery" "$out" "pacman -U /var/cache/pacman/pkg/linux-"
|
||||
}
|
||||
|
||||
test_help_and_bad_args() {
|
||||
echo "TEST: CLI contract"
|
||||
local out rc
|
||||
out="$("$BOOT_REPAIR" --help 2>&1)"
|
||||
rc=$?
|
||||
assert_eq "--help exits 0" "$rc" "0"
|
||||
assert_contains "help mentions dry-run" "$out" "--dry-run"
|
||||
|
||||
out="$("$BOOT_REPAIR" --nonsense 2>&1)"
|
||||
rc=$?
|
||||
assert_eq "unknown option exits 2" "$rc" "2"
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Runner
|
||||
|
||||
187
linux_configuration/scripts/single_use/features/lib/pi_flash_exec.sh
Executable file
187
linux_configuration/scripts/single_use/features/lib/pi_flash_exec.sh
Executable file
@ -0,0 +1,187 @@
|
||||
#!/bin/bash
|
||||
# Flashing from the remote laptop.
|
||||
#
|
||||
# Sourced by raspberry_pi_flash_sd.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# =============================================================================
|
||||
# Remote Flash
|
||||
# =============================================================================
|
||||
|
||||
phase_flash_remote() {
|
||||
log_info "=== Flash Raspberry Pi OS to SD Card on Remote Laptop ==="
|
||||
|
||||
discover_remote_laptop
|
||||
|
||||
setup_ssh_key_to_remote "$REMOTE_LAPTOP_IP" "$REMOTE_LAPTOP_USER"
|
||||
|
||||
local remote="${REMOTE_LAPTOP_USER}@${REMOTE_LAPTOP_IP}"
|
||||
|
||||
log_info "Checking for SD card on remote laptop..."
|
||||
echo "Block devices on ${remote}:"
|
||||
ssh "$remote" "lsblk -d -o NAME,SIZE,TYPE,RM,TRAN,MODEL" || true
|
||||
echo
|
||||
|
||||
log_info "Auto-detecting SD card on remote laptop..."
|
||||
local sd_device
|
||||
sd_device=$(ssh "$remote" "lsblk -d -o NAME,RM,TRAN | grep -E '1.*(usb|mmc)' | awk '{print \"/dev/\"\$1}' | head -1" 2> /dev/null || true)
|
||||
|
||||
if [[ -z $sd_device ]]; then
|
||||
die "No SD card detected on remote laptop. Please insert an SD card and try again."
|
||||
fi
|
||||
|
||||
local sd_info
|
||||
# shellcheck disable=SC2029 # Intentional client-side expansion
|
||||
sd_info=$(ssh "$remote" "lsblk -d -o NAME,SIZE,MODEL $sd_device 2>/dev/null | tail -1" || true)
|
||||
|
||||
log_success "Auto-detected SD card: $sd_device ($sd_info)"
|
||||
SD_CARD_DEVICE="$sd_device"
|
||||
|
||||
# shellcheck disable=SC2029 # Intentional client-side expansion
|
||||
if ! ssh "$remote" "[[ -b '$SD_CARD_DEVICE' ]]" 2> /dev/null; then
|
||||
die "Device $SD_CARD_DEVICE does not exist on remote laptop"
|
||||
fi
|
||||
|
||||
auto_generate_pi_password
|
||||
log_success "Pi user '$PI_USER' password: $PI_PASSWORD"
|
||||
|
||||
local encrypted_password
|
||||
encrypted_password=$(echo "$PI_PASSWORD" | openssl passwd -6 -stdin)
|
||||
|
||||
save_config
|
||||
|
||||
log_info "Copying script to remote laptop..."
|
||||
scp "$0" "${remote}:/tmp/raspberry_pi_flash_sd.sh"
|
||||
|
||||
log_info "Executing flash on remote laptop..."
|
||||
log_warning "This will ERASE ALL DATA on ${SD_CARD_DEVICE} on the remote laptop!"
|
||||
log_info "Proceeding automatically in 5 seconds... (Ctrl+C to cancel)"
|
||||
sleep 5
|
||||
|
||||
ssh -tt "$remote" "sudo SD_CARD_DEVICE='$SD_CARD_DEVICE' PI_USER='$PI_USER' PI_HOSTNAME='$PI_HOSTNAME' bash /tmp/raspberry_pi_flash_sd.sh execute-remote '$encrypted_password'"
|
||||
|
||||
log_success "Flash complete!"
|
||||
echo
|
||||
log_info "Pi credentials:"
|
||||
log_info " User: $PI_USER"
|
||||
log_info " Password: $PI_PASSWORD"
|
||||
log_info " Hostname: $PI_HOSTNAME"
|
||||
echo
|
||||
log_info "Next steps:"
|
||||
log_info "1. Remove SD card from the laptop and insert into Raspberry Pi"
|
||||
log_info "2. Connect the Pi to power and network"
|
||||
log_info "3. Wait 2-3 minutes for first boot"
|
||||
}
|
||||
|
||||
# Called on the remote laptop by phase_flash_remote
|
||||
phase_execute_remote() {
|
||||
check_root
|
||||
|
||||
local encrypted_password="${1:-}"
|
||||
|
||||
log_info "=== Executing Flash on Remote Laptop ==="
|
||||
|
||||
if [[ -z $SD_CARD_DEVICE ]]; then
|
||||
die "SD_CARD_DEVICE not set"
|
||||
fi
|
||||
|
||||
local image_path
|
||||
image_path=$(download_raspberry_pi_os)
|
||||
|
||||
log_info "Unmounting partitions on $SD_CARD_DEVICE..."
|
||||
for partition in "${SD_CARD_DEVICE}"*; do
|
||||
if mountpoint -q "$partition" 2> /dev/null || mount | grep -q "$partition"; then
|
||||
umount "$partition" 2> /dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_info "Flashing image to SD card..."
|
||||
dd if="$image_path" of="$SD_CARD_DEVICE" bs=4M status=progress conv=fsync
|
||||
sync
|
||||
log_success "Image flashed successfully!"
|
||||
|
||||
log_info "Configuring headless boot..."
|
||||
sleep 2
|
||||
partprobe "$SD_CARD_DEVICE" 2> /dev/null || true
|
||||
sleep 2
|
||||
|
||||
local boot_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}1"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}p1"
|
||||
else
|
||||
die "Could not find boot partition"
|
||||
fi
|
||||
|
||||
local boot_mount="/tmp/rpi-boot"
|
||||
mkdir -p "$boot_mount"
|
||||
mount "$boot_partition" "$boot_mount"
|
||||
|
||||
touch "$boot_mount/ssh"
|
||||
log_success "SSH enabled"
|
||||
|
||||
if [[ -n $encrypted_password ]]; then
|
||||
echo "${PI_USER}:${encrypted_password}" > "$boot_mount/userconf.txt"
|
||||
log_success "User '$PI_USER' configured"
|
||||
fi
|
||||
|
||||
local root_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}2"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}p2"
|
||||
fi
|
||||
|
||||
if [[ -n $root_partition ]]; then
|
||||
local root_mount="/tmp/rpi-root"
|
||||
mkdir -p "$root_mount"
|
||||
mount "$root_partition" "$root_mount"
|
||||
|
||||
echo "$PI_HOSTNAME" > "$root_mount/etc/hostname"
|
||||
sed -i "s/raspberrypi/$PI_HOSTNAME/g" "$root_mount/etc/hosts"
|
||||
|
||||
log_success "Hostname set to '$PI_HOSTNAME'"
|
||||
|
||||
umount "$root_mount"
|
||||
fi
|
||||
|
||||
umount "$boot_mount"
|
||||
sync
|
||||
|
||||
log_success "SD card configured for headless boot!"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Main
|
||||
# =============================================================================
|
||||
|
||||
show_help() {
|
||||
cat << 'EOF'
|
||||
Raspberry Pi SD Card Flash Script
|
||||
|
||||
Usage: ./raspberry_pi_flash_sd.sh <command>
|
||||
|
||||
Commands:
|
||||
local Flash SD card locally (requires root)
|
||||
remote Flash SD card on a remote laptop via SSH
|
||||
execute-remote Internal: executed on remote laptop
|
||||
help Show this help message
|
||||
|
||||
The script will:
|
||||
1. Auto-discover a remote laptop with an SD card (for remote mode)
|
||||
2. Download Raspberry Pi OS Lite (64-bit)
|
||||
3. Flash the image to the SD card
|
||||
4. Configure headless boot (SSH enabled, user created, hostname set)
|
||||
|
||||
Credentials are auto-generated and saved to .raspberry_pi.conf
|
||||
|
||||
Examples:
|
||||
# Flash locally (run as root)
|
||||
sudo ./raspberry_pi_flash_sd.sh local
|
||||
|
||||
# Flash on remote laptop
|
||||
./raspberry_pi_flash_sd.sh remote
|
||||
EOF
|
||||
}
|
||||
193
linux_configuration/scripts/single_use/features/lib/pi_flash_image.sh
Executable file
193
linux_configuration/scripts/single_use/features/lib/pi_flash_image.sh
Executable file
@ -0,0 +1,193 @@
|
||||
#!/bin/bash
|
||||
# OS image download and the local flash phase.
|
||||
#
|
||||
# Sourced by raspberry_pi_flash_sd.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
# =============================================================================
|
||||
# Download and Flash Functions
|
||||
# =============================================================================
|
||||
|
||||
download_raspberry_pi_os() {
|
||||
local download_dir="/tmp/rpi-image"
|
||||
local image_url="https://downloads.raspberrypi.com/raspios_lite_arm64/images/raspios_lite_arm64-2024-11-19/2024-11-19-raspios-bookworm-arm64-lite.img.xz"
|
||||
local image_file="$download_dir/raspios.img.xz"
|
||||
local extracted_image="$download_dir/raspios.img"
|
||||
local expected_size=459000608
|
||||
|
||||
mkdir -p "$download_dir"
|
||||
|
||||
if [[ -f $extracted_image ]]; then
|
||||
log_info "Using existing image at $extracted_image"
|
||||
echo "$extracted_image"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ -f $image_file ]]; then
|
||||
local actual_size
|
||||
actual_size=$(stat -c%s "$image_file" 2> /dev/null || stat -f%z "$image_file" 2> /dev/null || echo 0)
|
||||
if [[ $actual_size -lt $expected_size ]]; then
|
||||
log_warning "Incomplete download detected ($actual_size < $expected_size bytes), re-downloading..."
|
||||
rm -f "$image_file"
|
||||
else
|
||||
log_info "Image archive already downloaded"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ ! -f $image_file ]]; then
|
||||
log_info "Downloading Raspberry Pi OS Lite (64-bit)..."
|
||||
log_info "This may take a while depending on your internet connection..."
|
||||
|
||||
if command -v aria2c &> /dev/null; then
|
||||
aria2c -x 4 -c -d "$download_dir" --out="raspios.img.xz" "$image_url" >&2
|
||||
elif command -v wget &> /dev/null; then
|
||||
wget --continue --show-progress -O "$image_file" "$image_url" >&2
|
||||
elif command -v curl &> /dev/null; then
|
||||
curl -L -C - -o "$image_file" "$image_url" --progress-bar >&2
|
||||
else
|
||||
die "No download tool available. Install wget, curl, or aria2c"
|
||||
fi
|
||||
|
||||
local actual_size
|
||||
actual_size=$(stat -c%s "$image_file" 2> /dev/null || stat -f%z "$image_file" 2> /dev/null || echo 0)
|
||||
if [[ $actual_size -lt $expected_size ]]; then
|
||||
die "Download incomplete: got $actual_size bytes, expected $expected_size"
|
||||
fi
|
||||
log_success "Download complete: $actual_size bytes"
|
||||
fi
|
||||
|
||||
log_info "Extracting image..."
|
||||
xz -dk "$image_file"
|
||||
|
||||
if [[ ! -f $extracted_image ]]; then
|
||||
die "Failed to extract image"
|
||||
fi
|
||||
|
||||
echo "$extracted_image"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Local Flash
|
||||
# =============================================================================
|
||||
|
||||
phase_flash_local() {
|
||||
check_root
|
||||
|
||||
log_info "=== Flash Raspberry Pi OS to SD Card (Local) ==="
|
||||
|
||||
# Detect SD card
|
||||
log_info "Detecting removable storage devices..."
|
||||
local devices
|
||||
devices=$(lsblk -d -o NAME,SIZE,TYPE,RM,TRAN | grep -E "disk.*1.*usb|disk.*1.*mmc" | awk '{print "/dev/"$1" ("$2")"}')
|
||||
|
||||
if [[ -z $devices ]]; then
|
||||
log_warning "No removable devices detected automatically."
|
||||
lsblk -d -o NAME,SIZE,TYPE,RM,TRAN
|
||||
read -r -p "Enter the SD card device path (e.g., /dev/sdb): " SD_CARD_DEVICE
|
||||
else
|
||||
echo "Detected removable devices:"
|
||||
echo "$devices"
|
||||
read -r -p "Enter the SD card device path from above (e.g., /dev/sdb): " SD_CARD_DEVICE
|
||||
fi
|
||||
|
||||
if [[ ! -b $SD_CARD_DEVICE ]]; then
|
||||
die "Device $SD_CARD_DEVICE does not exist or is not a block device"
|
||||
fi
|
||||
|
||||
local root_device
|
||||
root_device=$(findmnt -n -o SOURCE / | sed 's/[0-9]*$//' | sed 's/p[0-9]*$//')
|
||||
if [[ $SD_CARD_DEVICE == "$root_device" ]]; then
|
||||
die "Cannot flash to the system drive!"
|
||||
fi
|
||||
|
||||
auto_generate_pi_password
|
||||
|
||||
local encrypted_password
|
||||
encrypted_password=$(echo "$PI_PASSWORD" | openssl passwd -6 -stdin)
|
||||
|
||||
save_config
|
||||
|
||||
local image_path
|
||||
image_path=$(download_raspberry_pi_os)
|
||||
|
||||
log_warning "This will ERASE ALL DATA on $SD_CARD_DEVICE"
|
||||
read -r -p "Are you sure you want to continue? (yes/no): " confirm
|
||||
|
||||
if [[ $confirm != "yes" ]]; then
|
||||
die "Aborted by user"
|
||||
fi
|
||||
|
||||
log_info "Unmounting partitions on $SD_CARD_DEVICE..."
|
||||
for partition in "${SD_CARD_DEVICE}"*; do
|
||||
if mountpoint -q "$partition" 2> /dev/null || mount | grep -q "$partition"; then
|
||||
umount "$partition" 2> /dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_info "Flashing image to SD card..."
|
||||
dd if="$image_path" of="$SD_CARD_DEVICE" bs=4M status=progress conv=fsync
|
||||
sync
|
||||
log_success "Image flashed successfully!"
|
||||
|
||||
# Configure headless boot
|
||||
log_info "Configuring headless boot..."
|
||||
sleep 2
|
||||
partprobe "$SD_CARD_DEVICE" 2> /dev/null || true
|
||||
sleep 2
|
||||
|
||||
local boot_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}1"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}p1"
|
||||
else
|
||||
die "Could not find boot partition"
|
||||
fi
|
||||
|
||||
local boot_mount="/tmp/rpi-boot"
|
||||
mkdir -p "$boot_mount"
|
||||
mount "$boot_partition" "$boot_mount"
|
||||
|
||||
touch "$boot_mount/ssh"
|
||||
log_success "SSH enabled"
|
||||
|
||||
echo "${PI_USER}:${encrypted_password}" > "$boot_mount/userconf.txt"
|
||||
log_success "User '$PI_USER' configured"
|
||||
|
||||
local root_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}2"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}p2"
|
||||
fi
|
||||
|
||||
if [[ -n $root_partition ]]; then
|
||||
local root_mount="/tmp/rpi-root"
|
||||
mkdir -p "$root_mount"
|
||||
mount "$root_partition" "$root_mount"
|
||||
|
||||
echo "$PI_HOSTNAME" > "$root_mount/etc/hostname"
|
||||
sed -i "s/raspberrypi/$PI_HOSTNAME/g" "$root_mount/etc/hosts"
|
||||
|
||||
log_success "Hostname set to '$PI_HOSTNAME'"
|
||||
|
||||
umount "$root_mount"
|
||||
fi
|
||||
|
||||
umount "$boot_mount"
|
||||
sync
|
||||
|
||||
log_success "SD card configured for headless boot!"
|
||||
log_success "Flash complete!"
|
||||
echo
|
||||
log_info "Pi credentials:"
|
||||
log_info " User: $PI_USER"
|
||||
log_info " Password: $PI_PASSWORD"
|
||||
log_info " Hostname: $PI_HOSTNAME"
|
||||
echo
|
||||
log_info "Next steps:"
|
||||
log_info "1. Remove SD card and insert into Raspberry Pi"
|
||||
log_info "2. Connect the Pi to power and network"
|
||||
log_info "3. Wait 2-3 minutes for first boot"
|
||||
}
|
||||
141
linux_configuration/scripts/single_use/features/lib/pi_flash_remote.sh
Executable file
141
linux_configuration/scripts/single_use/features/lib/pi_flash_remote.sh
Executable file
@ -0,0 +1,141 @@
|
||||
#!/bin/bash
|
||||
# Remote laptop discovery and SSH key setup.
|
||||
#
|
||||
# Sourced by raspberry_pi_flash_sd.sh; split out to keep it under the 250-line
|
||||
# cap. Sourced rather than run, so it inherits the caller's strict mode
|
||||
# and the variables defined above the source line.
|
||||
|
||||
discover_remote_laptop() {
|
||||
log_info "Auto-discovering remote laptop on local network..."
|
||||
|
||||
ensure_dependencies
|
||||
|
||||
local my_ip
|
||||
my_ip=$(ip -4 addr show | grep -oP '(?<=inet\s)(?!127\.)\d+(\.\d+){3}' | head -1)
|
||||
|
||||
local gateway
|
||||
gateway=$(ip route | grep default | awk '{print $3}' | head -1)
|
||||
local network="${gateway%.*}.0/24"
|
||||
|
||||
log_info "Local IP: $my_ip, Gateway: $gateway, Network: $network"
|
||||
log_info "Scanning network for SSH-enabled devices (using nmap)..."
|
||||
|
||||
local ssh_hosts
|
||||
nmap -sn -T4 "$network" &> /dev/null || true
|
||||
ssh_hosts=$(nmap -p 22 --open -sT -T4 "$network" 2> /dev/null | grep "Nmap scan report" | grep -oP '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | grep -vw "$my_ip" | sort -u)
|
||||
|
||||
if [[ -z $ssh_hosts ]]; then
|
||||
die "No SSH-enabled devices found on network"
|
||||
fi
|
||||
|
||||
local host_count
|
||||
host_count=$(echo "$ssh_hosts" | wc -l)
|
||||
log_info "Found $host_count SSH-enabled device(s): $(echo "$ssh_hosts" | tr '\n' ' ')"
|
||||
|
||||
local common_users=("$REMOTE_LAPTOP_USER" "kuchy" "kuhy" "$(whoami)" "pi" "user" "admin")
|
||||
local users=()
|
||||
for u in "${common_users[@]}"; do
|
||||
local is_dup=0
|
||||
for existing in "${users[@]}"; do
|
||||
if [[ $u == "$existing" ]]; then
|
||||
is_dup=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [[ $is_dup -eq 0 ]]; then
|
||||
users+=("$u")
|
||||
fi
|
||||
done
|
||||
|
||||
log_info "Will try usernames: ${users[*]}"
|
||||
|
||||
local found_laptop=""
|
||||
local found_user=""
|
||||
local idx=0
|
||||
|
||||
for ip in $ssh_hosts; do
|
||||
idx=$((idx + 1))
|
||||
|
||||
if [[ $ip == "$gateway" ]]; then
|
||||
log_info "[$idx/$host_count] Skipping $ip (gateway)"
|
||||
continue
|
||||
fi
|
||||
|
||||
log_info "[$idx/$host_count] $ip - Trying SSH key access with common usernames..."
|
||||
|
||||
for try_user in "${users[@]}"; do
|
||||
if ssh -o BatchMode=yes -o ConnectTimeout=2 -o StrictHostKeyChecking=accept-new "${try_user}@${ip}" "echo ok" 2> /dev/null | grep -q "ok"; then
|
||||
log_success "[$idx/$host_count] $ip - SSH key access confirmed with user '$try_user'!"
|
||||
found_user="$try_user"
|
||||
|
||||
log_info "[$idx/$host_count] $ip - Checking for SD card..."
|
||||
local has_sd
|
||||
has_sd=$(ssh -o BatchMode=yes -o ConnectTimeout=2 "${try_user}@${ip}" "lsblk -d -o NAME,RM,TRAN 2>/dev/null | grep -E '1.*(usb|mmc)' | head -1" 2> /dev/null || true)
|
||||
|
||||
if [[ -n $has_sd ]]; then
|
||||
log_success "[$idx/$host_count] $ip - Found SD card: $has_sd"
|
||||
found_laptop="$ip"
|
||||
break 2
|
||||
else
|
||||
log_warning "[$idx/$host_count] $ip - No SD card detected, saving as fallback..."
|
||||
if [[ -z $found_laptop ]]; then
|
||||
found_laptop="$ip"
|
||||
fi
|
||||
fi
|
||||
break
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
if [[ -z $found_laptop ]] || [[ -z $found_user ]]; then
|
||||
log_warning "No device with passwordless SSH found using common usernames."
|
||||
|
||||
found_laptop=$(echo "$ssh_hosts" | grep -vw "$gateway" | head -1)
|
||||
|
||||
if [[ -z $found_laptop ]]; then
|
||||
die "Could not find any suitable SSH-enabled device"
|
||||
fi
|
||||
|
||||
log_info "Found SSH host at $found_laptop but need credentials."
|
||||
read -r -p "Enter username for $found_laptop: " found_user
|
||||
|
||||
if [[ -z $found_user ]]; then
|
||||
die "No username provided"
|
||||
fi
|
||||
fi
|
||||
|
||||
REMOTE_LAPTOP_IP="$found_laptop"
|
||||
REMOTE_LAPTOP_USER="$found_user"
|
||||
log_success "Selected remote laptop: ${REMOTE_LAPTOP_USER}@${REMOTE_LAPTOP_IP}"
|
||||
|
||||
save_config
|
||||
}
|
||||
|
||||
setup_ssh_key_to_remote() {
|
||||
local remote_host="$1"
|
||||
local remote_user="$2"
|
||||
|
||||
if ssh -o BatchMode=yes -o ConnectTimeout=5 "${remote_user}@${remote_host}" "echo 'SSH key works'" 2> /dev/null; then
|
||||
log_success "SSH key authentication to ${remote_user}@${remote_host} already configured"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "Setting up SSH key authentication to ${remote_user}@${remote_host}..."
|
||||
|
||||
if [[ ! -f ~/.ssh/id_rsa.pub ]] && [[ ! -f ~/.ssh/id_ed25519.pub ]]; then
|
||||
log_info "Generating SSH key..."
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N "" -q
|
||||
fi
|
||||
|
||||
log_info "Copying SSH key to remote host (you may be prompted for password)..."
|
||||
|
||||
if command -v ssh-copy-id &> /dev/null; then
|
||||
ssh-copy-id -o StrictHostKeyChecking=no "${remote_user}@${remote_host}"
|
||||
else
|
||||
local pub_key
|
||||
pub_key=$(cat ~/.ssh/id_ed25519.pub 2> /dev/null || cat ~/.ssh/id_rsa.pub)
|
||||
ssh -o StrictHostKeyChecking=no "${remote_user}@${remote_host}" "mkdir -p ~/.ssh && echo '$pub_key' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
|
||||
fi
|
||||
|
||||
log_success "SSH key authentication configured"
|
||||
}
|
||||
@ -131,508 +131,13 @@ ensure_dependencies() {
|
||||
fi
|
||||
}
|
||||
|
||||
discover_remote_laptop() {
|
||||
log_info "Auto-discovering remote laptop on local network..."
|
||||
# shellcheck source=lib/pi_flash_remote.sh
|
||||
source "$SCRIPT_DIR/lib/pi_flash_remote.sh"
|
||||
# shellcheck source=lib/pi_flash_image.sh
|
||||
source "$SCRIPT_DIR/lib/pi_flash_image.sh"
|
||||
# shellcheck source=lib/pi_flash_exec.sh
|
||||
source "$SCRIPT_DIR/lib/pi_flash_exec.sh"
|
||||
|
||||
ensure_dependencies
|
||||
|
||||
local my_ip
|
||||
my_ip=$(ip -4 addr show | grep -oP '(?<=inet\s)(?!127\.)\d+(\.\d+){3}' | head -1)
|
||||
|
||||
local gateway
|
||||
gateway=$(ip route | grep default | awk '{print $3}' | head -1)
|
||||
local network="${gateway%.*}.0/24"
|
||||
|
||||
log_info "Local IP: $my_ip, Gateway: $gateway, Network: $network"
|
||||
log_info "Scanning network for SSH-enabled devices (using nmap)..."
|
||||
|
||||
local ssh_hosts
|
||||
nmap -sn -T4 "$network" &> /dev/null || true
|
||||
ssh_hosts=$(nmap -p 22 --open -sT -T4 "$network" 2> /dev/null | grep "Nmap scan report" | grep -oP '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | grep -vw "$my_ip" | sort -u)
|
||||
|
||||
if [[ -z $ssh_hosts ]]; then
|
||||
die "No SSH-enabled devices found on network"
|
||||
fi
|
||||
|
||||
local host_count
|
||||
host_count=$(echo "$ssh_hosts" | wc -l)
|
||||
log_info "Found $host_count SSH-enabled device(s): $(echo "$ssh_hosts" | tr '\n' ' ')"
|
||||
|
||||
local common_users=("$REMOTE_LAPTOP_USER" "kuchy" "kuhy" "$(whoami)" "pi" "user" "admin")
|
||||
local users=()
|
||||
for u in "${common_users[@]}"; do
|
||||
local is_dup=0
|
||||
for existing in "${users[@]}"; do
|
||||
if [[ $u == "$existing" ]]; then
|
||||
is_dup=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [[ $is_dup -eq 0 ]]; then
|
||||
users+=("$u")
|
||||
fi
|
||||
done
|
||||
|
||||
log_info "Will try usernames: ${users[*]}"
|
||||
|
||||
local found_laptop=""
|
||||
local found_user=""
|
||||
local idx=0
|
||||
|
||||
for ip in $ssh_hosts; do
|
||||
idx=$((idx + 1))
|
||||
|
||||
if [[ $ip == "$gateway" ]]; then
|
||||
log_info "[$idx/$host_count] Skipping $ip (gateway)"
|
||||
continue
|
||||
fi
|
||||
|
||||
log_info "[$idx/$host_count] $ip - Trying SSH key access with common usernames..."
|
||||
|
||||
for try_user in "${users[@]}"; do
|
||||
if ssh -o BatchMode=yes -o ConnectTimeout=2 -o StrictHostKeyChecking=accept-new "${try_user}@${ip}" "echo ok" 2> /dev/null | grep -q "ok"; then
|
||||
log_success "[$idx/$host_count] $ip - SSH key access confirmed with user '$try_user'!"
|
||||
found_user="$try_user"
|
||||
|
||||
log_info "[$idx/$host_count] $ip - Checking for SD card..."
|
||||
local has_sd
|
||||
has_sd=$(ssh -o BatchMode=yes -o ConnectTimeout=2 "${try_user}@${ip}" "lsblk -d -o NAME,RM,TRAN 2>/dev/null | grep -E '1.*(usb|mmc)' | head -1" 2> /dev/null || true)
|
||||
|
||||
if [[ -n $has_sd ]]; then
|
||||
log_success "[$idx/$host_count] $ip - Found SD card: $has_sd"
|
||||
found_laptop="$ip"
|
||||
break 2
|
||||
else
|
||||
log_warning "[$idx/$host_count] $ip - No SD card detected, saving as fallback..."
|
||||
if [[ -z $found_laptop ]]; then
|
||||
found_laptop="$ip"
|
||||
fi
|
||||
fi
|
||||
break
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
if [[ -z $found_laptop ]] || [[ -z $found_user ]]; then
|
||||
log_warning "No device with passwordless SSH found using common usernames."
|
||||
|
||||
found_laptop=$(echo "$ssh_hosts" | grep -vw "$gateway" | head -1)
|
||||
|
||||
if [[ -z $found_laptop ]]; then
|
||||
die "Could not find any suitable SSH-enabled device"
|
||||
fi
|
||||
|
||||
log_info "Found SSH host at $found_laptop but need credentials."
|
||||
read -r -p "Enter username for $found_laptop: " found_user
|
||||
|
||||
if [[ -z $found_user ]]; then
|
||||
die "No username provided"
|
||||
fi
|
||||
fi
|
||||
|
||||
REMOTE_LAPTOP_IP="$found_laptop"
|
||||
REMOTE_LAPTOP_USER="$found_user"
|
||||
log_success "Selected remote laptop: ${REMOTE_LAPTOP_USER}@${REMOTE_LAPTOP_IP}"
|
||||
|
||||
save_config
|
||||
}
|
||||
|
||||
setup_ssh_key_to_remote() {
|
||||
local remote_host="$1"
|
||||
local remote_user="$2"
|
||||
|
||||
if ssh -o BatchMode=yes -o ConnectTimeout=5 "${remote_user}@${remote_host}" "echo 'SSH key works'" 2> /dev/null; then
|
||||
log_success "SSH key authentication to ${remote_user}@${remote_host} already configured"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_info "Setting up SSH key authentication to ${remote_user}@${remote_host}..."
|
||||
|
||||
if [[ ! -f ~/.ssh/id_rsa.pub ]] && [[ ! -f ~/.ssh/id_ed25519.pub ]]; then
|
||||
log_info "Generating SSH key..."
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N "" -q
|
||||
fi
|
||||
|
||||
log_info "Copying SSH key to remote host (you may be prompted for password)..."
|
||||
|
||||
if command -v ssh-copy-id &> /dev/null; then
|
||||
ssh-copy-id -o StrictHostKeyChecking=no "${remote_user}@${remote_host}"
|
||||
else
|
||||
local pub_key
|
||||
pub_key=$(cat ~/.ssh/id_ed25519.pub 2> /dev/null || cat ~/.ssh/id_rsa.pub)
|
||||
ssh -o StrictHostKeyChecking=no "${remote_user}@${remote_host}" "mkdir -p ~/.ssh && echo '$pub_key' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
|
||||
fi
|
||||
|
||||
log_success "SSH key authentication configured"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Download and Flash Functions
|
||||
# =============================================================================
|
||||
|
||||
download_raspberry_pi_os() {
|
||||
local download_dir="/tmp/rpi-image"
|
||||
local image_url="https://downloads.raspberrypi.com/raspios_lite_arm64/images/raspios_lite_arm64-2024-11-19/2024-11-19-raspios-bookworm-arm64-lite.img.xz"
|
||||
local image_file="$download_dir/raspios.img.xz"
|
||||
local extracted_image="$download_dir/raspios.img"
|
||||
local expected_size=459000608
|
||||
|
||||
mkdir -p "$download_dir"
|
||||
|
||||
if [[ -f $extracted_image ]]; then
|
||||
log_info "Using existing image at $extracted_image"
|
||||
echo "$extracted_image"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ -f $image_file ]]; then
|
||||
local actual_size
|
||||
actual_size=$(stat -c%s "$image_file" 2> /dev/null || stat -f%z "$image_file" 2> /dev/null || echo 0)
|
||||
if [[ $actual_size -lt $expected_size ]]; then
|
||||
log_warning "Incomplete download detected ($actual_size < $expected_size bytes), re-downloading..."
|
||||
rm -f "$image_file"
|
||||
else
|
||||
log_info "Image archive already downloaded"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ ! -f $image_file ]]; then
|
||||
log_info "Downloading Raspberry Pi OS Lite (64-bit)..."
|
||||
log_info "This may take a while depending on your internet connection..."
|
||||
|
||||
if command -v aria2c &> /dev/null; then
|
||||
aria2c -x 4 -c -d "$download_dir" --out="raspios.img.xz" "$image_url" >&2
|
||||
elif command -v wget &> /dev/null; then
|
||||
wget --continue --show-progress -O "$image_file" "$image_url" >&2
|
||||
elif command -v curl &> /dev/null; then
|
||||
curl -L -C - -o "$image_file" "$image_url" --progress-bar >&2
|
||||
else
|
||||
die "No download tool available. Install wget, curl, or aria2c"
|
||||
fi
|
||||
|
||||
local actual_size
|
||||
actual_size=$(stat -c%s "$image_file" 2> /dev/null || stat -f%z "$image_file" 2> /dev/null || echo 0)
|
||||
if [[ $actual_size -lt $expected_size ]]; then
|
||||
die "Download incomplete: got $actual_size bytes, expected $expected_size"
|
||||
fi
|
||||
log_success "Download complete: $actual_size bytes"
|
||||
fi
|
||||
|
||||
log_info "Extracting image..."
|
||||
xz -dk "$image_file"
|
||||
|
||||
if [[ ! -f $extracted_image ]]; then
|
||||
die "Failed to extract image"
|
||||
fi
|
||||
|
||||
echo "$extracted_image"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Local Flash
|
||||
# =============================================================================
|
||||
|
||||
phase_flash_local() {
|
||||
check_root
|
||||
|
||||
log_info "=== Flash Raspberry Pi OS to SD Card (Local) ==="
|
||||
|
||||
# Detect SD card
|
||||
log_info "Detecting removable storage devices..."
|
||||
local devices
|
||||
devices=$(lsblk -d -o NAME,SIZE,TYPE,RM,TRAN | grep -E "disk.*1.*usb|disk.*1.*mmc" | awk '{print "/dev/"$1" ("$2")"}')
|
||||
|
||||
if [[ -z $devices ]]; then
|
||||
log_warning "No removable devices detected automatically."
|
||||
lsblk -d -o NAME,SIZE,TYPE,RM,TRAN
|
||||
read -r -p "Enter the SD card device path (e.g., /dev/sdb): " SD_CARD_DEVICE
|
||||
else
|
||||
echo "Detected removable devices:"
|
||||
echo "$devices"
|
||||
read -r -p "Enter the SD card device path from above (e.g., /dev/sdb): " SD_CARD_DEVICE
|
||||
fi
|
||||
|
||||
if [[ ! -b $SD_CARD_DEVICE ]]; then
|
||||
die "Device $SD_CARD_DEVICE does not exist or is not a block device"
|
||||
fi
|
||||
|
||||
local root_device
|
||||
root_device=$(findmnt -n -o SOURCE / | sed 's/[0-9]*$//' | sed 's/p[0-9]*$//')
|
||||
if [[ $SD_CARD_DEVICE == "$root_device" ]]; then
|
||||
die "Cannot flash to the system drive!"
|
||||
fi
|
||||
|
||||
auto_generate_pi_password
|
||||
|
||||
local encrypted_password
|
||||
encrypted_password=$(echo "$PI_PASSWORD" | openssl passwd -6 -stdin)
|
||||
|
||||
save_config
|
||||
|
||||
local image_path
|
||||
image_path=$(download_raspberry_pi_os)
|
||||
|
||||
log_warning "This will ERASE ALL DATA on $SD_CARD_DEVICE"
|
||||
read -r -p "Are you sure you want to continue? (yes/no): " confirm
|
||||
|
||||
if [[ $confirm != "yes" ]]; then
|
||||
die "Aborted by user"
|
||||
fi
|
||||
|
||||
log_info "Unmounting partitions on $SD_CARD_DEVICE..."
|
||||
for partition in "${SD_CARD_DEVICE}"*; do
|
||||
if mountpoint -q "$partition" 2> /dev/null || mount | grep -q "$partition"; then
|
||||
umount "$partition" 2> /dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_info "Flashing image to SD card..."
|
||||
dd if="$image_path" of="$SD_CARD_DEVICE" bs=4M status=progress conv=fsync
|
||||
sync
|
||||
log_success "Image flashed successfully!"
|
||||
|
||||
# Configure headless boot
|
||||
log_info "Configuring headless boot..."
|
||||
sleep 2
|
||||
partprobe "$SD_CARD_DEVICE" 2> /dev/null || true
|
||||
sleep 2
|
||||
|
||||
local boot_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}1"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}p1"
|
||||
else
|
||||
die "Could not find boot partition"
|
||||
fi
|
||||
|
||||
local boot_mount="/tmp/rpi-boot"
|
||||
mkdir -p "$boot_mount"
|
||||
mount "$boot_partition" "$boot_mount"
|
||||
|
||||
touch "$boot_mount/ssh"
|
||||
log_success "SSH enabled"
|
||||
|
||||
echo "${PI_USER}:${encrypted_password}" > "$boot_mount/userconf.txt"
|
||||
log_success "User '$PI_USER' configured"
|
||||
|
||||
local root_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}2"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}p2"
|
||||
fi
|
||||
|
||||
if [[ -n $root_partition ]]; then
|
||||
local root_mount="/tmp/rpi-root"
|
||||
mkdir -p "$root_mount"
|
||||
mount "$root_partition" "$root_mount"
|
||||
|
||||
echo "$PI_HOSTNAME" > "$root_mount/etc/hostname"
|
||||
sed -i "s/raspberrypi/$PI_HOSTNAME/g" "$root_mount/etc/hosts"
|
||||
|
||||
log_success "Hostname set to '$PI_HOSTNAME'"
|
||||
|
||||
umount "$root_mount"
|
||||
fi
|
||||
|
||||
umount "$boot_mount"
|
||||
sync
|
||||
|
||||
log_success "SD card configured for headless boot!"
|
||||
log_success "Flash complete!"
|
||||
echo
|
||||
log_info "Pi credentials:"
|
||||
log_info " User: $PI_USER"
|
||||
log_info " Password: $PI_PASSWORD"
|
||||
log_info " Hostname: $PI_HOSTNAME"
|
||||
echo
|
||||
log_info "Next steps:"
|
||||
log_info "1. Remove SD card and insert into Raspberry Pi"
|
||||
log_info "2. Connect the Pi to power and network"
|
||||
log_info "3. Wait 2-3 minutes for first boot"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Remote Flash
|
||||
# =============================================================================
|
||||
|
||||
phase_flash_remote() {
|
||||
log_info "=== Flash Raspberry Pi OS to SD Card on Remote Laptop ==="
|
||||
|
||||
discover_remote_laptop
|
||||
|
||||
setup_ssh_key_to_remote "$REMOTE_LAPTOP_IP" "$REMOTE_LAPTOP_USER"
|
||||
|
||||
local remote="${REMOTE_LAPTOP_USER}@${REMOTE_LAPTOP_IP}"
|
||||
|
||||
log_info "Checking for SD card on remote laptop..."
|
||||
echo "Block devices on ${remote}:"
|
||||
ssh "$remote" "lsblk -d -o NAME,SIZE,TYPE,RM,TRAN,MODEL" || true
|
||||
echo
|
||||
|
||||
log_info "Auto-detecting SD card on remote laptop..."
|
||||
local sd_device
|
||||
sd_device=$(ssh "$remote" "lsblk -d -o NAME,RM,TRAN | grep -E '1.*(usb|mmc)' | awk '{print \"/dev/\"\$1}' | head -1" 2> /dev/null || true)
|
||||
|
||||
if [[ -z $sd_device ]]; then
|
||||
die "No SD card detected on remote laptop. Please insert an SD card and try again."
|
||||
fi
|
||||
|
||||
local sd_info
|
||||
# shellcheck disable=SC2029 # Intentional client-side expansion
|
||||
sd_info=$(ssh "$remote" "lsblk -d -o NAME,SIZE,MODEL $sd_device 2>/dev/null | tail -1" || true)
|
||||
|
||||
log_success "Auto-detected SD card: $sd_device ($sd_info)"
|
||||
SD_CARD_DEVICE="$sd_device"
|
||||
|
||||
# shellcheck disable=SC2029 # Intentional client-side expansion
|
||||
if ! ssh "$remote" "[[ -b '$SD_CARD_DEVICE' ]]" 2> /dev/null; then
|
||||
die "Device $SD_CARD_DEVICE does not exist on remote laptop"
|
||||
fi
|
||||
|
||||
auto_generate_pi_password
|
||||
log_success "Pi user '$PI_USER' password: $PI_PASSWORD"
|
||||
|
||||
local encrypted_password
|
||||
encrypted_password=$(echo "$PI_PASSWORD" | openssl passwd -6 -stdin)
|
||||
|
||||
save_config
|
||||
|
||||
log_info "Copying script to remote laptop..."
|
||||
scp "$0" "${remote}:/tmp/raspberry_pi_flash_sd.sh"
|
||||
|
||||
log_info "Executing flash on remote laptop..."
|
||||
log_warning "This will ERASE ALL DATA on ${SD_CARD_DEVICE} on the remote laptop!"
|
||||
log_info "Proceeding automatically in 5 seconds... (Ctrl+C to cancel)"
|
||||
sleep 5
|
||||
|
||||
ssh -tt "$remote" "sudo SD_CARD_DEVICE='$SD_CARD_DEVICE' PI_USER='$PI_USER' PI_HOSTNAME='$PI_HOSTNAME' bash /tmp/raspberry_pi_flash_sd.sh execute-remote '$encrypted_password'"
|
||||
|
||||
log_success "Flash complete!"
|
||||
echo
|
||||
log_info "Pi credentials:"
|
||||
log_info " User: $PI_USER"
|
||||
log_info " Password: $PI_PASSWORD"
|
||||
log_info " Hostname: $PI_HOSTNAME"
|
||||
echo
|
||||
log_info "Next steps:"
|
||||
log_info "1. Remove SD card from the laptop and insert into Raspberry Pi"
|
||||
log_info "2. Connect the Pi to power and network"
|
||||
log_info "3. Wait 2-3 minutes for first boot"
|
||||
}
|
||||
|
||||
# Called on the remote laptop by phase_flash_remote
|
||||
phase_execute_remote() {
|
||||
check_root
|
||||
|
||||
local encrypted_password="${1:-}"
|
||||
|
||||
log_info "=== Executing Flash on Remote Laptop ==="
|
||||
|
||||
if [[ -z $SD_CARD_DEVICE ]]; then
|
||||
die "SD_CARD_DEVICE not set"
|
||||
fi
|
||||
|
||||
local image_path
|
||||
image_path=$(download_raspberry_pi_os)
|
||||
|
||||
log_info "Unmounting partitions on $SD_CARD_DEVICE..."
|
||||
for partition in "${SD_CARD_DEVICE}"*; do
|
||||
if mountpoint -q "$partition" 2> /dev/null || mount | grep -q "$partition"; then
|
||||
umount "$partition" 2> /dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
log_info "Flashing image to SD card..."
|
||||
dd if="$image_path" of="$SD_CARD_DEVICE" bs=4M status=progress conv=fsync
|
||||
sync
|
||||
log_success "Image flashed successfully!"
|
||||
|
||||
log_info "Configuring headless boot..."
|
||||
sleep 2
|
||||
partprobe "$SD_CARD_DEVICE" 2> /dev/null || true
|
||||
sleep 2
|
||||
|
||||
local boot_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}1"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p1" ]]; then
|
||||
boot_partition="${SD_CARD_DEVICE}p1"
|
||||
else
|
||||
die "Could not find boot partition"
|
||||
fi
|
||||
|
||||
local boot_mount="/tmp/rpi-boot"
|
||||
mkdir -p "$boot_mount"
|
||||
mount "$boot_partition" "$boot_mount"
|
||||
|
||||
touch "$boot_mount/ssh"
|
||||
log_success "SSH enabled"
|
||||
|
||||
if [[ -n $encrypted_password ]]; then
|
||||
echo "${PI_USER}:${encrypted_password}" > "$boot_mount/userconf.txt"
|
||||
log_success "User '$PI_USER' configured"
|
||||
fi
|
||||
|
||||
local root_partition
|
||||
if [[ -b "${SD_CARD_DEVICE}2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}2"
|
||||
elif [[ -b "${SD_CARD_DEVICE}p2" ]]; then
|
||||
root_partition="${SD_CARD_DEVICE}p2"
|
||||
fi
|
||||
|
||||
if [[ -n $root_partition ]]; then
|
||||
local root_mount="/tmp/rpi-root"
|
||||
mkdir -p "$root_mount"
|
||||
mount "$root_partition" "$root_mount"
|
||||
|
||||
echo "$PI_HOSTNAME" > "$root_mount/etc/hostname"
|
||||
sed -i "s/raspberrypi/$PI_HOSTNAME/g" "$root_mount/etc/hosts"
|
||||
|
||||
log_success "Hostname set to '$PI_HOSTNAME'"
|
||||
|
||||
umount "$root_mount"
|
||||
fi
|
||||
|
||||
umount "$boot_mount"
|
||||
sync
|
||||
|
||||
log_success "SD card configured for headless boot!"
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Main
|
||||
# =============================================================================
|
||||
|
||||
show_help() {
|
||||
cat << 'EOF'
|
||||
Raspberry Pi SD Card Flash Script
|
||||
|
||||
Usage: ./raspberry_pi_flash_sd.sh <command>
|
||||
|
||||
Commands:
|
||||
local Flash SD card locally (requires root)
|
||||
remote Flash SD card on a remote laptop via SSH
|
||||
execute-remote Internal: executed on remote laptop
|
||||
help Show this help message
|
||||
|
||||
The script will:
|
||||
1. Auto-discover a remote laptop with an SD card (for remote mode)
|
||||
2. Download Raspberry Pi OS Lite (64-bit)
|
||||
3. Flash the image to the SD card
|
||||
4. Configure headless boot (SSH enabled, user created, hostname set)
|
||||
|
||||
Credentials are auto-generated and saved to .raspberry_pi.conf
|
||||
|
||||
Examples:
|
||||
# Flash locally (run as root)
|
||||
sudo ./raspberry_pi_flash_sd.sh local
|
||||
|
||||
# Flash on remote laptop
|
||||
./raspberry_pi_flash_sd.sh remote
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
local command="${1:-help}"
|
||||
|
||||
@ -6,8 +6,8 @@
|
||||
|
||||
## Where things stand
|
||||
|
||||
**92 files** over 250 lines (was 183 — exactly half cleared). Everything is
|
||||
committed and pushed to `main` at `776e04d`; the tree is clean.
|
||||
**83 files** over 250 lines (was 183). Everything is committed and pushed to
|
||||
`main` at `093e2f6`; the tree is clean.
|
||||
|
||||
**`python_pkg/` is DONE — 50 violations → 0.** Do not reopen it. Cleared one
|
||||
package per tranche, pushing after each: `brother_printer` (15→0, suite pinned
|
||||
@ -15,16 +15,13 @@ at 402), `code_tutor` (13→0, 216→217), then `android_ui`, `app_icons`,
|
||||
`token_audit`, `focus_policy`, `random_jpg` (57/44/81/137/14), then
|
||||
`wsg_grabber`'s six test modules (277).
|
||||
|
||||
**`linux_configuration` is 84 → 49**, in eleven batches. **All 12 prose files
|
||||
**`linux_configuration` is 84 → 42**, in fourteen batches. **All 12 prose files
|
||||
are done** (8 split, 2 deleted as completed-work records on the user's ruling).
|
||||
**`kcd2_dice_solver` is 12 → 4**, all four remaining being source files. The
|
||||
shell pattern is settled and scripted — read `docs/shell-split-recipes.md`
|
||||
before touching another one.
|
||||
|
||||
**Four deferred for shared state across the seam** in `kcd2_dice_solver` and
|
||||
`linux_configuration` alike (see the table below); the TypeScript ones are
|
||||
`search.ts` (findBestSet ⇄ hillClimb) and `badgeValue.ts` (valueBadge ⇄
|
||||
format). In TS a bad seam **compiles clean and fails at runtime** — an import
|
||||
In TypeScript a bad seam **compiles clean and fails at runtime** — an import
|
||||
cycle leaves a constant `undefined` at module-init. Always run the suite.
|
||||
|
||||
Earlier sessions had already done: the `~/utils` exemptions, the
|
||||
@ -35,35 +32,38 @@ Earlier sessions had already done: the `~/utils` exemptions, the
|
||||
|
||||
## What is left
|
||||
|
||||
| Directory | Count |
|
||||
| ------------------------------------- | ------------ |
|
||||
| `linux_configuration` | 49 |
|
||||
| `phone_focus_mode` | 12 (do LAST) |
|
||||
| `kcd2_dice_solver` | 4 |
|
||||
| `focus_owner` | 11 |
|
||||
| `billsplit` | 6 |
|
||||
| `reverse_survivors` / `meta` / `docs` | 4 each |
|
||||
| `.github` / `bucket_catch` | 2 each |
|
||||
| Directory | Count |
|
||||
| ---------------------------------- | ------------ |
|
||||
| `linux_configuration` | 42 |
|
||||
| `phone_focus_mode` | 12 (do LAST) |
|
||||
| `focus_owner` | 11 |
|
||||
| `billsplit` | 6 |
|
||||
| `meta` / `kcd2_dice_solver` | 4 each |
|
||||
| `reverse_survivors`/`bucket_catch` | 2 each |
|
||||
|
||||
**Four `linux_configuration` files are deliberately over the cap**, all for
|
||||
one reason: **state crosses the seam.** Pass it explicitly first, then split;
|
||||
never suppress. See "When to give up on a seam".
|
||||
|
||||
| File | Why |
|
||||
| ------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `steam_compatibility.sh` (663) | `CACHE_MAP` assoc array written in a lib, read by `main` |
|
||||
| `diagnose_pacman_hook_stall.sh` (493) | assigns `LAST_ELAPSED` the caller reads, reads `PACMAN_BIN` it defines |
|
||||
| `clean_audio.sh` (419) | probe-result globals threaded through two libs |
|
||||
| `setup_passwordless_system.sh` (374) | no `main()`; top-level block must be kept by hand |
|
||||
| File | Why |
|
||||
| ------------------------------------- | -------------------------------------------- |
|
||||
| `check_and_enable_services.sh` (1337) | every `check_*` writes one `SERVICE_STATUS` |
|
||||
| `steam_compatibility.sh` (663) | `CACHE_MAP` written in a lib, read by `main` |
|
||||
| `diagnose_pacman_hook_stall.sh` (493) | `LAST_ELAPSED` / `PACMAN_BIN` cross the seam |
|
||||
| `libre_translate.sh` (488) | ~19 globals cross any seam |
|
||||
| `enforce_vbox_hosts.sh` (443) | every seam falls inside a heredoc |
|
||||
| `clean_audio.sh` (419) | probe-result globals through two libs |
|
||||
| `setup_passwordless_system.sh` (374) | no `main()`; top-level block kept by hand |
|
||||
|
||||
**The pre-commit `shellcheck` hook lints each lib in isolation**, with no view
|
||||
of the caller's globals. That is stricter than `shellcheck -x` on the entry
|
||||
script and is the check that decides whether a seam is real — run
|
||||
`pre-commit run shellcheck --files <all touched>` before believing a split.
|
||||
Same in TypeScript: `kcd2`'s `search.ts` and `badgeValue.ts`, and
|
||||
`reverse_survivors`' `sim.ts` (`step` ⇄ `survivorStep`) and `types.ts`.
|
||||
|
||||
Next: the remaining `main()`-shaped shell scripts, then
|
||||
`kcd2_dice_solver` / `focus_owner` / `billsplit` (TS+Dart+Kotlin, untouched so
|
||||
far), then the four prose files — zero execution risk.
|
||||
**The pre-commit `shellcheck` hook lints each lib alone**, with no view of the
|
||||
caller's globals — stricter than `shellcheck -x` on the entry, and the check
|
||||
that decides whether a seam is real. Run it before believing a split.
|
||||
|
||||
Next: the remaining `main()`-shaped shell scripts, then `focus_owner` and
|
||||
`billsplit` (Kotlin+Dart, untouched so far — check for a test command first).
|
||||
|
||||
## The live worklist
|
||||
|
||||
|
||||
@ -4,9 +4,7 @@ import { createInitialState } from './sim'
|
||||
import { snapshotOf } from './snapshot'
|
||||
import type { GameState } from './types'
|
||||
import {
|
||||
AMBUSH_RADIUS, ARENA, BOSS_COOLDOWN, ENEMY_SPECS, ENERGY_CAP, FRENZY_DURATION,
|
||||
POWER_COOLDOWN, POWER_COST, RIFT_DURATION,
|
||||
} from './types'
|
||||
ARENA, BOSS_COOLDOWN, ENERGY_CAP, } from './types'
|
||||
|
||||
const fresh = (seed = 1): GameState => createInitialState(seed)
|
||||
|
||||
@ -172,144 +170,3 @@ describe('snapshot', () => {
|
||||
expect(snapshotOf(s).survivorHp).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('director powers', () => {
|
||||
it('power cooldowns drain and floor at zero', () => {
|
||||
const s = fresh()
|
||||
s.director.powerCooldowns.ambush = 0.3
|
||||
s.director.powerCooldowns.frenzy = 2
|
||||
tickDirector(s, 0.5)
|
||||
expect(s.director.powerCooldowns.ambush).toBe(0)
|
||||
expect(s.director.powerCooldowns.frenzy).toBeCloseTo(1.5)
|
||||
})
|
||||
|
||||
it('frenzy and rift timers drain and floor at zero', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 0.2
|
||||
s.director.riftTimer = 5
|
||||
tickDirector(s, 0.5)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
expect(s.director.riftTimer).toBeCloseTo(4.5)
|
||||
})
|
||||
|
||||
it('ambush lands a unit near the survivor and debits both costs', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(true)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
const e = s.enemies[0]
|
||||
const d = Math.hypot(
|
||||
(e?.pos.x ?? 0) - s.survivor.pos.x,
|
||||
(e?.pos.y ?? 0) - s.survivor.pos.y,
|
||||
)
|
||||
expect(d).toBeCloseTo(AMBUSH_RADIUS, 5)
|
||||
expect(s.director.energy).toBe(400 - POWER_COST.ambush - ENEMY_SPECS.rusher.cost)
|
||||
expect(s.director.powerCooldowns.ambush).toBe(POWER_COOLDOWN.ambush)
|
||||
})
|
||||
|
||||
it('ambush is rejected when it cannot be afforded', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 5
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(false)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
expect(s.director.energy).toBe(5)
|
||||
})
|
||||
|
||||
it('ambush is rejected while cooling', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(true)
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(false)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ambush lanes never repeat, even past a full turn', () => {
|
||||
// Regression: a 2*PI/7 step cycled silently, so index 7 reused index 0.
|
||||
const s = fresh()
|
||||
const seen: string[] = []
|
||||
for (let i = 0; i < 24; i += 1) {
|
||||
s.director.powerCooldowns.ambush = 0
|
||||
s.director.energy = 400
|
||||
s.enemies = []
|
||||
applyAction(s, { type: 'ambush', kind: 'rusher' })
|
||||
const e = s.enemies[0]
|
||||
seen.push(`${(e?.pos.x ?? 0).toFixed(6)},${(e?.pos.y ?? 0).toFixed(6)}`)
|
||||
}
|
||||
expect(new Set(seen).size).toBe(24)
|
||||
})
|
||||
|
||||
it('successive ambushes rotate to a different lane, deterministically', () => {
|
||||
const angles = (): number[] => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
s.director.powerCooldowns.ambush = 0
|
||||
s.director.energy = 400
|
||||
applyAction(s, { type: 'ambush', kind: 'rusher' })
|
||||
}
|
||||
for (const e of s.enemies) {
|
||||
out.push(Math.atan2(e.pos.y - s.survivor.pos.y, e.pos.x - s.survivor.pos.x))
|
||||
}
|
||||
return out
|
||||
}
|
||||
const first = angles()
|
||||
expect(new Set(first).size).toBe(3)
|
||||
expect(angles()).toEqual(first)
|
||||
})
|
||||
|
||||
it('frenzy sets its timer and debits the cost', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'frenzy' })).toBe(true)
|
||||
expect(s.director.frenzyTimer).toBe(FRENZY_DURATION)
|
||||
expect(s.director.energy).toBe(400 - POWER_COST.frenzy)
|
||||
})
|
||||
|
||||
it('frenzy is rejected when unaffordable', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 10
|
||||
expect(applyAction(s, { type: 'frenzy' })).toBe(false)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
})
|
||||
|
||||
it('a rift pins every spawn to the chosen edge', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'rift', edge: 2 })).toBe(true)
|
||||
expect(s.director.riftTimer).toBe(RIFT_DURATION)
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
expect(edgeSpawnPos(s).x).toBe(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('once the rift closes, all four edges return', () => {
|
||||
const s = fresh(7)
|
||||
s.director.riftTimer = 0
|
||||
const seen = new Set<string>()
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
const p = edgeSpawnPos(s)
|
||||
seen.add(`${String(p.x === 0 || p.x === ARENA.w)}-${String(p.y === 0 || p.y === ARENA.h)}`)
|
||||
}
|
||||
expect(seen.size).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('a rift is rejected when unaffordable', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 1
|
||||
expect(applyAction(s, { type: 'rift', edge: 1 })).toBe(false)
|
||||
expect(s.director.riftTimer).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('difficulty economy', () => {
|
||||
it('regen defaults to a rate of 1', () => {
|
||||
expect(regenRate(0)).toBe(6)
|
||||
expect(regenRate(30)).toBe(8)
|
||||
})
|
||||
|
||||
it('regen scales with the tier rate', () => {
|
||||
expect(regenRate(0, 1.25)).toBeCloseTo(7.5)
|
||||
expect(regenRate(0, 0.85)).toBeCloseTo(5.1)
|
||||
})
|
||||
})
|
||||
|
||||
153
reverse_survivors/src/core/directorPowers.test.ts
Normal file
153
reverse_survivors/src/core/directorPowers.test.ts
Normal file
@ -0,0 +1,153 @@
|
||||
/** Director powers and difficulty economy. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyAction, edgeSpawnPos, regenRate, tickDirector, } from './director'
|
||||
import { createInitialState } from './sim'
|
||||
import type { GameState } from './types'
|
||||
import {
|
||||
AMBUSH_RADIUS, ARENA, ENEMY_SPECS, FRENZY_DURATION,
|
||||
POWER_COOLDOWN, POWER_COST, RIFT_DURATION,
|
||||
} from './types'
|
||||
|
||||
const fresh = (seed = 1): GameState => createInitialState(seed)
|
||||
|
||||
describe('director powers', () => {
|
||||
it('power cooldowns drain and floor at zero', () => {
|
||||
const s = fresh()
|
||||
s.director.powerCooldowns.ambush = 0.3
|
||||
s.director.powerCooldowns.frenzy = 2
|
||||
tickDirector(s, 0.5)
|
||||
expect(s.director.powerCooldowns.ambush).toBe(0)
|
||||
expect(s.director.powerCooldowns.frenzy).toBeCloseTo(1.5)
|
||||
})
|
||||
|
||||
it('frenzy and rift timers drain and floor at zero', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 0.2
|
||||
s.director.riftTimer = 5
|
||||
tickDirector(s, 0.5)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
expect(s.director.riftTimer).toBeCloseTo(4.5)
|
||||
})
|
||||
|
||||
it('ambush lands a unit near the survivor and debits both costs', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(true)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
const e = s.enemies[0]
|
||||
const d = Math.hypot(
|
||||
(e?.pos.x ?? 0) - s.survivor.pos.x,
|
||||
(e?.pos.y ?? 0) - s.survivor.pos.y,
|
||||
)
|
||||
expect(d).toBeCloseTo(AMBUSH_RADIUS, 5)
|
||||
expect(s.director.energy).toBe(400 - POWER_COST.ambush - ENEMY_SPECS.rusher.cost)
|
||||
expect(s.director.powerCooldowns.ambush).toBe(POWER_COOLDOWN.ambush)
|
||||
})
|
||||
|
||||
it('ambush is rejected when it cannot be afforded', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 5
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(false)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
expect(s.director.energy).toBe(5)
|
||||
})
|
||||
|
||||
it('ambush is rejected while cooling', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(true)
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(false)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ambush lanes never repeat, even past a full turn', () => {
|
||||
// Regression: a 2*PI/7 step cycled silently, so index 7 reused index 0.
|
||||
const s = fresh()
|
||||
const seen: string[] = []
|
||||
for (let i = 0; i < 24; i += 1) {
|
||||
s.director.powerCooldowns.ambush = 0
|
||||
s.director.energy = 400
|
||||
s.enemies = []
|
||||
applyAction(s, { type: 'ambush', kind: 'rusher' })
|
||||
const e = s.enemies[0]
|
||||
seen.push(`${(e?.pos.x ?? 0).toFixed(6)},${(e?.pos.y ?? 0).toFixed(6)}`)
|
||||
}
|
||||
expect(new Set(seen).size).toBe(24)
|
||||
})
|
||||
|
||||
it('successive ambushes rotate to a different lane, deterministically', () => {
|
||||
const angles = (): number[] => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
s.director.powerCooldowns.ambush = 0
|
||||
s.director.energy = 400
|
||||
applyAction(s, { type: 'ambush', kind: 'rusher' })
|
||||
}
|
||||
for (const e of s.enemies) {
|
||||
out.push(Math.atan2(e.pos.y - s.survivor.pos.y, e.pos.x - s.survivor.pos.x))
|
||||
}
|
||||
return out
|
||||
}
|
||||
const first = angles()
|
||||
expect(new Set(first).size).toBe(3)
|
||||
expect(angles()).toEqual(first)
|
||||
})
|
||||
|
||||
it('frenzy sets its timer and debits the cost', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'frenzy' })).toBe(true)
|
||||
expect(s.director.frenzyTimer).toBe(FRENZY_DURATION)
|
||||
expect(s.director.energy).toBe(400 - POWER_COST.frenzy)
|
||||
})
|
||||
|
||||
it('frenzy is rejected when unaffordable', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 10
|
||||
expect(applyAction(s, { type: 'frenzy' })).toBe(false)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
})
|
||||
|
||||
it('a rift pins every spawn to the chosen edge', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'rift', edge: 2 })).toBe(true)
|
||||
expect(s.director.riftTimer).toBe(RIFT_DURATION)
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
expect(edgeSpawnPos(s).x).toBe(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('once the rift closes, all four edges return', () => {
|
||||
const s = fresh(7)
|
||||
s.director.riftTimer = 0
|
||||
const seen = new Set<string>()
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
const p = edgeSpawnPos(s)
|
||||
seen.add(`${String(p.x === 0 || p.x === ARENA.w)}-${String(p.y === 0 || p.y === ARENA.h)}`)
|
||||
}
|
||||
expect(seen.size).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('a rift is rejected when unaffordable', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 1
|
||||
expect(applyAction(s, { type: 'rift', edge: 1 })).toBe(false)
|
||||
expect(s.director.riftTimer).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('difficulty economy', () => {
|
||||
it('regen defaults to a rate of 1', () => {
|
||||
expect(regenRate(0)).toBe(6)
|
||||
expect(regenRate(30)).toBe(8)
|
||||
})
|
||||
|
||||
it('regen scales with the tier rate', () => {
|
||||
expect(regenRate(0, 1.25)).toBeCloseTo(7.5)
|
||||
expect(regenRate(0, 0.85)).toBeCloseTo(5.1)
|
||||
})
|
||||
})
|
||||
@ -1,34 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyUpgrade, createInitialState, DANGER_RADIUS, grantXp, makeEnemy, SPLIT_RADIUS, step,
|
||||
applyUpgrade, createInitialState, DANGER_RADIUS, grantXp, makeEnemy, step,
|
||||
xpForLevel,
|
||||
} from './sim'
|
||||
import type { GameState, Projectile } from './types'
|
||||
import type { GameState, } from './types'
|
||||
import {
|
||||
ARENA, DIFFICULTIES, FRENZY_DAMAGE, FRENZY_SPEED, GAME_DURATION, STATUS_POWER,
|
||||
} from './types'
|
||||
ARENA, GAME_DURATION, } from './types'
|
||||
|
||||
const CENTER = { x: ARENA.w / 2, y: ARENA.h / 2 }
|
||||
|
||||
const fresh = (seed = 1, duration?: number): GameState =>
|
||||
duration === undefined ? createInitialState(seed) : createInitialState(seed, duration)
|
||||
|
||||
const shot = (state: GameState, x: number, y: number, damage: number): Projectile => {
|
||||
const p: Projectile = {
|
||||
id: state.nextId,
|
||||
from: 'survivor',
|
||||
pos: { x, y },
|
||||
vel: { x: 0, y: 0 },
|
||||
radius: 4,
|
||||
damage,
|
||||
ttl: 1,
|
||||
debuff: 'slow',
|
||||
debuffDuration: 0,
|
||||
}
|
||||
state.nextId += 1
|
||||
state.projectiles.push(p)
|
||||
return p
|
||||
}
|
||||
|
||||
describe('createInitialState', () => {
|
||||
it('uses the default duration when omitted', () => {
|
||||
@ -170,529 +153,3 @@ describe('survivor firing', () => {
|
||||
expect(s.projectiles).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('enemy behaviors', () => {
|
||||
it('chasers close the distance', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.1)
|
||||
expect(e.pos.x).toBeLessThan(CENTER.x + 300)
|
||||
})
|
||||
|
||||
it('melee contact damages the survivor once per cooldown window', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 6)
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 6)
|
||||
})
|
||||
|
||||
it('tank hits harder', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 5, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 14)
|
||||
})
|
||||
|
||||
it('stalker approaches when too far', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'stalker', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
expect(e.pos.x).toBeLessThan(CENTER.x + 300)
|
||||
})
|
||||
|
||||
it('stalker retreats when too close', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'stalker', { x: CENTER.x + 100, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
expect(e.pos.x).toBeGreaterThan(CENTER.x + 100)
|
||||
})
|
||||
|
||||
it('stalker holds position inside its comfort band', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'stalker', { x: CENTER.x + 160, y: CENTER.y })
|
||||
const before = e.pos.x
|
||||
step(s, [], 0.05)
|
||||
expect(e.pos.x).toBe(before)
|
||||
})
|
||||
|
||||
it('stalker fires when in range and ready, then cools down', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'stalker', { x: CENTER.x + 220, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles.filter((p) => p.from === 'enemy')).toHaveLength(1)
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles.filter((p) => p.from === 'enemy')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('stalker does not fire from beyond its range', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'stalker', { x: CENTER.x + 400, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles.filter((p) => p.from === 'enemy')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('hivemind emits a rusher on its spawn cadence', () => {
|
||||
const s = fresh()
|
||||
const hive = makeEnemy(s, 'hivemind', { x: 900, y: 560 })
|
||||
step(s, [], 2.5)
|
||||
expect(s.enemies.filter((e) => e.kind === 'rusher')).toHaveLength(1)
|
||||
expect(hive.spawnTimer).toBe(2.5)
|
||||
step(s, [], 0.1)
|
||||
expect(s.enemies.filter((e) => e.kind === 'rusher')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bomber', () => {
|
||||
it('detonates on contact: damages the survivor, dies, grants nothing', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'bomber', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 22)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
expect(s.survivor.kills).toBe(0)
|
||||
expect(s.survivor.xp).toBe(0)
|
||||
})
|
||||
|
||||
it('sniped from afar: grants xp, blast misses the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'bomber', { x: CENTER.x + 300, y: CENTER.y })
|
||||
shot(s, CENTER.x + 300, CENTER.y, 99)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(1)
|
||||
expect(s.survivor.xp).toBe(10)
|
||||
expect(s.survivor.hp).toBe(100)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shot inside blast range: grants xp and still burns the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'bomber', { x: CENTER.x + 30, y: CENTER.y })
|
||||
shot(s, CENTER.x + 30, CENTER.y, 99)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(1)
|
||||
expect(s.survivor.hp).toBeCloseTo(100 - 22, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('projectiles', () => {
|
||||
it('expire by ttl', () => {
|
||||
const s = fresh()
|
||||
shot(s, 50, 50, 1)
|
||||
step(s, [], 2)
|
||||
expect(s.projectiles).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('a miss keeps flying', () => {
|
||||
const s = fresh()
|
||||
shot(s, 50, 50, 1)
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('damages without killing when the target outlasts the hit', () => {
|
||||
const s = fresh()
|
||||
const tank = makeEnemy(s, 'tank', { x: CENTER.x + 400, y: CENTER.y })
|
||||
shot(s, CENTER.x + 400, CENTER.y, 8)
|
||||
step(s, [], 0.001)
|
||||
expect(tank.hp).toBe(112)
|
||||
expect(s.survivor.kills).toBe(0)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('a second projectile in the same tick passes through an already-dead target', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x + 400, y: CENTER.y })
|
||||
shot(s, CENTER.x + 400, CENTER.y, 20)
|
||||
shot(s, CENTER.x + 400, CENTER.y, 20)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(1)
|
||||
expect(s.projectiles).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('enemy fire hurts the survivor', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 500, from: 'enemy', pos: { x: CENTER.x, y: CENTER.y },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 7, ttl: 1,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
})
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.hp).toBe(93)
|
||||
expect(s.projectiles).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('enemy fire that misses keeps flying', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 501, from: 'enemy', pos: { x: 30, y: 30 },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 7, ttl: 1,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
})
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.hp).toBe(100)
|
||||
expect(s.projectiles).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('game end', () => {
|
||||
it('director wins when the survivor drops to zero', () => {
|
||||
const s = fresh()
|
||||
s.survivor.hp = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.status).toBe('directorWon')
|
||||
expect(s.outcomeTime).toBeCloseTo(0.01)
|
||||
})
|
||||
|
||||
it('survivor wins when the clock runs out', () => {
|
||||
const s = fresh(1, 0.05)
|
||||
step(s, [], 0.1)
|
||||
expect(s.status).toBe('survivorWon')
|
||||
})
|
||||
|
||||
it('a kill on the final tick still counts as a director win', () => {
|
||||
const s = fresh(1, 0.05)
|
||||
s.survivor.hp = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.1)
|
||||
expect(s.status).toBe('directorWon')
|
||||
})
|
||||
|
||||
it('a finished game is inert', () => {
|
||||
const s = fresh(1, 0.05)
|
||||
step(s, [], 0.1)
|
||||
const t = s.t
|
||||
step(s, [], 0.1)
|
||||
expect(s.t).toBe(t)
|
||||
})
|
||||
|
||||
it('director actions flow through step', () => {
|
||||
const s = fresh()
|
||||
step(s, [{ type: 'spawn', kind: 'rusher' }], 0.001)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
expect(s.director.energy).toBeLessThan(30)
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitter', () => {
|
||||
it('dies into three rushers at fixed offsets', () => {
|
||||
const s = fresh()
|
||||
const sp = makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
const children = s.enemies.filter((e) => e.id !== sp.id)
|
||||
expect(children).toHaveLength(3)
|
||||
expect(children.every((c) => c.kind === 'rusher')).toBe(true)
|
||||
// Children drift toward the survivor within the same tick, so assert the
|
||||
// spawn ring loosely — the exact geometry is pinned by the test below.
|
||||
for (const c of children) {
|
||||
expect(Math.hypot(c.pos.x - 300, c.pos.y - 300)).toBeLessThan(SPLIT_RADIUS + 5)
|
||||
}
|
||||
})
|
||||
|
||||
it('spawns children on a ring at 120-degree offsets', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
// dt of 0 isolates the spawn geometry from the movement that follows it.
|
||||
step(s, [], 0)
|
||||
const angles = s.enemies
|
||||
.map((e) => Math.atan2(e.pos.y - 300, e.pos.x - 300))
|
||||
.sort((a, b) => a - b)
|
||||
expect(angles).toHaveLength(3)
|
||||
// Pairwise gaps without indexing (noUncheckedIndexedAccess would widen those).
|
||||
const gaps: number[] = []
|
||||
let prev: number | null = null
|
||||
for (const a of angles) {
|
||||
if (prev !== null) {
|
||||
gaps.push(a - prev)
|
||||
}
|
||||
prev = a
|
||||
}
|
||||
expect(gaps).toHaveLength(2)
|
||||
for (const g of gaps) {
|
||||
expect(g).toBeCloseTo((Math.PI * 2) / 3, 5)
|
||||
}
|
||||
})
|
||||
|
||||
it('children are deterministic and draw no RNG', () => {
|
||||
const run = (): { x: number; y: number }[] => {
|
||||
const s = fresh(42)
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
return s.enemies.map((e) => ({ x: e.pos.x, y: e.pos.y }))
|
||||
}
|
||||
expect(run()).toEqual(run())
|
||||
})
|
||||
|
||||
it('clamps children into the arena when it dies in a corner', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 2, y: 2 })
|
||||
shot(s, 2, 2, 999)
|
||||
step(s, [], 0.001)
|
||||
for (const e of s.enemies) {
|
||||
expect(e.pos.x).toBeGreaterThanOrEqual(10)
|
||||
expect(e.pos.y).toBeGreaterThanOrEqual(10)
|
||||
}
|
||||
})
|
||||
|
||||
it('a later projectile in the same tick can hit a fresh child', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
shot(s, 300 + SPLIT_RADIUS, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(2)
|
||||
})
|
||||
|
||||
it('non-splitting kinds spawn no children', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('new units', () => {
|
||||
it('artillery outranges the survivor and fires while it cannot', () => {
|
||||
const s = fresh()
|
||||
const a = makeEnemy(s, 'artillery', { x: CENTER.x + 400, y: CENTER.y })
|
||||
a.fireTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.projectiles.some((p) => p.from === 'enemy')).toBe(true)
|
||||
expect(s.projectiles.some((p) => p.from === 'survivor')).toBe(false)
|
||||
})
|
||||
|
||||
it('artillery holds station at its keep distance', () => {
|
||||
const s = fresh()
|
||||
const a = makeEnemy(s, 'artillery', { x: CENTER.x + 420, y: CENTER.y })
|
||||
const before = a.pos.x
|
||||
step(s, [], 0.016)
|
||||
expect(a.pos.x).toBeCloseTo(before, 5)
|
||||
})
|
||||
|
||||
it('warden closes faster than a rusher', () => {
|
||||
const s = fresh()
|
||||
const w = makeEnemy(s, 'warden', { x: CENTER.x + 300, y: CENTER.y })
|
||||
const r = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.016)
|
||||
expect(CENTER.x + 300 - w.pos.x).toBeGreaterThan(CENTER.x + 300 - r.pos.x)
|
||||
})
|
||||
|
||||
it('the hivemind still births rushers via spawnKind', () => {
|
||||
const s = fresh()
|
||||
const h = makeEnemy(s, 'hivemind', { x: 40, y: 40 })
|
||||
h.spawnTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.enemies.some((e) => e.kind === 'rusher')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('status effects', () => {
|
||||
it('a warden contact mires the survivor and halves its movement', () => {
|
||||
const slowed = fresh()
|
||||
slowed.survivor.pos = { x: 100, y: CENTER.y }
|
||||
makeEnemy(slowed, 'warden', { x: 100, y: CENTER.y })
|
||||
step(slowed, [], 0.01)
|
||||
// Statuses tick in survivorStep, which runs before enemiesStep applies
|
||||
// contact — so a status landing this tick starts at its full duration.
|
||||
expect(slowed.survivor.statuses.slow).toBe(2.0)
|
||||
|
||||
// Control: same displacement, an enemy that inflicts nothing.
|
||||
const control = fresh()
|
||||
control.survivor.pos = { x: 100, y: CENTER.y }
|
||||
makeEnemy(control, 'rusher', { x: 100, y: CENTER.y })
|
||||
step(control, [], 0.01)
|
||||
expect(control.survivor.statuses.slow).toBe(0)
|
||||
|
||||
const before = { slowed: slowed.survivor.pos.x, control: control.survivor.pos.x }
|
||||
slowed.enemies = []
|
||||
control.enemies = []
|
||||
step(slowed, [], 0.05)
|
||||
step(control, [], 0.05)
|
||||
const movedSlowed = slowed.survivor.pos.x - before.slowed
|
||||
const movedControl = control.survivor.pos.x - before.control
|
||||
expect(movedSlowed).toBeCloseTo(movedControl * STATUS_POWER.slow, 5)
|
||||
})
|
||||
|
||||
it('slow expires and full speed returns', () => {
|
||||
const s = fresh()
|
||||
s.survivor.pos = { x: 100, y: CENTER.y }
|
||||
s.survivor.statuses.slow = 0.02
|
||||
step(s, [], 0.05)
|
||||
expect(s.survivor.statuses.slow).toBe(0)
|
||||
})
|
||||
|
||||
it('an artillery shell stifles the survivor and lengthens its reload', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 900, from: 'enemy', pos: { x: CENTER.x, y: CENTER.y },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 13, ttl: 1,
|
||||
debuff: 'suppress', debuffDuration: 2.5,
|
||||
})
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 200, y: CENTER.y })
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.statuses.suppress).toBeGreaterThan(0)
|
||||
// The shot fired this tick reloaded before the status landed; the next one pays.
|
||||
s.survivor.fireTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.fireTimer).toBeCloseTo(0.55 * STATUS_POWER.suppress, 5)
|
||||
})
|
||||
|
||||
it('a leech contact blocks regeneration until it expires', () => {
|
||||
const s = fresh()
|
||||
s.survivor.regen = 5
|
||||
s.survivor.hp = 50
|
||||
makeEnemy(s, 'leech', { x: CENTER.x, y: CENTER.y })
|
||||
const hp0 = s.survivor.hp
|
||||
step(s, [], 0.1)
|
||||
// Contact damage lands and regen is suppressed, so hp cannot have risen.
|
||||
expect(s.survivor.hp).toBeLessThan(hp0)
|
||||
expect(s.survivor.statuses.bleed).toBeGreaterThan(0)
|
||||
|
||||
s.enemies = []
|
||||
s.survivor.statuses.bleed = 0
|
||||
const hp1 = s.survivor.hp
|
||||
step(s, [], 0.1)
|
||||
expect(s.survivor.hp).toBeGreaterThan(hp1)
|
||||
})
|
||||
|
||||
it('repeated warden contacts refresh rather than stack', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'warden', { x: CENTER.x, y: CENTER.y })
|
||||
makeEnemy(s, 'warden', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.statuses.slow).toBeLessThanOrEqual(2.0)
|
||||
})
|
||||
|
||||
it('a plain rusher inflicts no status at all', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.statuses).toEqual({ slow: 0, suppress: 0, bleed: 0 })
|
||||
})
|
||||
|
||||
it('survivor fire never debuffs the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 200, y: CENTER.y })
|
||||
step(s, [], 0.001)
|
||||
const own = s.projectiles.find((p) => p.from === 'survivor')
|
||||
expect(own?.debuffDuration).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('frenzy', () => {
|
||||
it('speeds the horde while it lasts', () => {
|
||||
const base = fresh()
|
||||
const b = makeEnemy(base, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(base, [], 0.05)
|
||||
const normal = CENTER.x + 300 - b.pos.x
|
||||
|
||||
const hyped = fresh()
|
||||
hyped.director.frenzyTimer = 5
|
||||
const h = makeEnemy(hyped, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(hyped, [], 0.05)
|
||||
const rushed = CENTER.x + 300 - h.pos.x
|
||||
|
||||
expect(rushed).toBeCloseTo(normal * FRENZY_SPEED, 5)
|
||||
})
|
||||
|
||||
it('raises contact damage while it lasts', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBeCloseTo(100 - 6 * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('expires back to baseline speed', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 0.01
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.5)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
const after = e.pos.x
|
||||
step(s, [], 0.05)
|
||||
const moved = after - e.pos.x
|
||||
expect(moved).toBeCloseTo(170 * 0.05, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('difficulty tiers', () => {
|
||||
it('defaults to normal, the identity tier', () => {
|
||||
const s = fresh()
|
||||
expect(s.difficulty).toBe(DIFFICULTIES.normal)
|
||||
expect(s.survivor.maxHp).toBe(100)
|
||||
})
|
||||
|
||||
it('accepts an explicit tier', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
expect(s.difficulty).toBe(DIFFICULTIES.crusade)
|
||||
})
|
||||
|
||||
it('takes its duration from the tier when none is given', () => {
|
||||
expect(createInitialState(1, undefined, 'haunting').duration)
|
||||
.toBe(DIFFICULTIES.haunting.duration)
|
||||
})
|
||||
|
||||
it('an explicit duration still wins over the tier', () => {
|
||||
expect(createInitialState(1, 42, 'haunting').duration).toBe(42)
|
||||
})
|
||||
|
||||
it('scales enemy hp', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
const e = makeEnemy(s, 'rusher', { x: 0, y: 0 })
|
||||
expect(e.hp).toBeCloseTo(14 * DIFFICULTIES.crusade.enemyHp, 5)
|
||||
})
|
||||
|
||||
it('scales survivor hp', () => {
|
||||
const s = createInitialState(1, undefined, 'haunting')
|
||||
expect(s.survivor.maxHp).toBe(125)
|
||||
})
|
||||
|
||||
it('scales enemy speed', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
const moved = CENTER.x + 300 - e.pos.x
|
||||
expect(moved).toBeCloseTo(170 * DIFFICULTIES.crusade.enemySpeed * 0.05, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('frenzy damage reaches every channel', () => {
|
||||
// Regression: frenzy multiplied contact damage only, so ranged and blast
|
||||
// units — including the bomber, whose whole purpose is damage — ignored it.
|
||||
const dealt = (frenzied: boolean, kind: 'warden' | 'artillery' | 'bomber', at: number): number => {
|
||||
const s = fresh(3)
|
||||
s.survivor.hp = 1e6
|
||||
s.survivor.maxHp = 1e6
|
||||
s.survivor.speed = 0
|
||||
s.duration = 1e6
|
||||
if (frenzied) {
|
||||
s.director.frenzyTimer = 1e6
|
||||
}
|
||||
makeEnemy(s, kind, { x: CENTER.x + at, y: CENTER.y })
|
||||
const before = s.survivor.hp
|
||||
for (let i = 0; i < 360; i += 1) {
|
||||
step(s, [], 1 / 60)
|
||||
}
|
||||
return before - s.survivor.hp
|
||||
}
|
||||
|
||||
it('scales contact damage', () => {
|
||||
expect(dealt(true, 'warden', 0)).toBeCloseTo(dealt(false, 'warden', 0) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('scales ranged damage', () => {
|
||||
expect(dealt(true, 'artillery', 300))
|
||||
.toBeCloseTo(dealt(false, 'artillery', 300) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('scales blast damage', () => {
|
||||
expect(dealt(true, 'bomber', 0)).toBeCloseTo(dealt(false, 'bomber', 0) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
})
|
||||
|
||||
236
reverse_survivors/src/core/simEnemies.test.ts
Normal file
236
reverse_survivors/src/core/simEnemies.test.ts
Normal file
@ -0,0 +1,236 @@
|
||||
/** Enemy behaviour, bombers and projectiles. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createInitialState, makeEnemy, step,
|
||||
} from './sim'
|
||||
import type { GameState, Projectile } from './types'
|
||||
import {
|
||||
ARENA, } from './types'
|
||||
|
||||
const CENTER = { x: ARENA.w / 2, y: ARENA.h / 2 }
|
||||
|
||||
const fresh = (seed = 1, duration?: number): GameState =>
|
||||
duration === undefined ? createInitialState(seed) : createInitialState(seed, duration)
|
||||
|
||||
const shot = (state: GameState, x: number, y: number, damage: number): Projectile => {
|
||||
const p: Projectile = {
|
||||
id: state.nextId,
|
||||
from: 'survivor',
|
||||
pos: { x, y },
|
||||
vel: { x: 0, y: 0 },
|
||||
radius: 4,
|
||||
damage,
|
||||
ttl: 1,
|
||||
debuff: 'slow',
|
||||
debuffDuration: 0,
|
||||
}
|
||||
state.nextId += 1
|
||||
state.projectiles.push(p)
|
||||
return p
|
||||
}
|
||||
|
||||
describe('enemy behaviors', () => {
|
||||
it('chasers close the distance', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.1)
|
||||
expect(e.pos.x).toBeLessThan(CENTER.x + 300)
|
||||
})
|
||||
|
||||
it('melee contact damages the survivor once per cooldown window', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 6)
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 6)
|
||||
})
|
||||
|
||||
it('tank hits harder', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 5, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 14)
|
||||
})
|
||||
|
||||
it('stalker approaches when too far', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'stalker', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
expect(e.pos.x).toBeLessThan(CENTER.x + 300)
|
||||
})
|
||||
|
||||
it('stalker retreats when too close', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'stalker', { x: CENTER.x + 100, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
expect(e.pos.x).toBeGreaterThan(CENTER.x + 100)
|
||||
})
|
||||
|
||||
it('stalker holds position inside its comfort band', () => {
|
||||
const s = fresh()
|
||||
const e = makeEnemy(s, 'stalker', { x: CENTER.x + 160, y: CENTER.y })
|
||||
const before = e.pos.x
|
||||
step(s, [], 0.05)
|
||||
expect(e.pos.x).toBe(before)
|
||||
})
|
||||
|
||||
it('stalker fires when in range and ready, then cools down', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'stalker', { x: CENTER.x + 220, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles.filter((p) => p.from === 'enemy')).toHaveLength(1)
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles.filter((p) => p.from === 'enemy')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('stalker does not fire from beyond its range', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'stalker', { x: CENTER.x + 400, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles.filter((p) => p.from === 'enemy')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('hivemind emits a rusher on its spawn cadence', () => {
|
||||
const s = fresh()
|
||||
const hive = makeEnemy(s, 'hivemind', { x: 900, y: 560 })
|
||||
step(s, [], 2.5)
|
||||
expect(s.enemies.filter((e) => e.kind === 'rusher')).toHaveLength(1)
|
||||
expect(hive.spawnTimer).toBe(2.5)
|
||||
step(s, [], 0.1)
|
||||
expect(s.enemies.filter((e) => e.kind === 'rusher')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('bomber', () => {
|
||||
it('detonates on contact: damages the survivor, dies, grants nothing', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'bomber', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBe(100 - 22)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
expect(s.survivor.kills).toBe(0)
|
||||
expect(s.survivor.xp).toBe(0)
|
||||
})
|
||||
|
||||
it('sniped from afar: grants xp, blast misses the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'bomber', { x: CENTER.x + 300, y: CENTER.y })
|
||||
shot(s, CENTER.x + 300, CENTER.y, 99)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(1)
|
||||
expect(s.survivor.xp).toBe(10)
|
||||
expect(s.survivor.hp).toBe(100)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shot inside blast range: grants xp and still burns the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'bomber', { x: CENTER.x + 30, y: CENTER.y })
|
||||
shot(s, CENTER.x + 30, CENTER.y, 99)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(1)
|
||||
expect(s.survivor.hp).toBeCloseTo(100 - 22, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('projectiles', () => {
|
||||
it('expire by ttl', () => {
|
||||
const s = fresh()
|
||||
shot(s, 50, 50, 1)
|
||||
step(s, [], 2)
|
||||
expect(s.projectiles).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('a miss keeps flying', () => {
|
||||
const s = fresh()
|
||||
shot(s, 50, 50, 1)
|
||||
step(s, [], 0.01)
|
||||
expect(s.projectiles).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('damages without killing when the target outlasts the hit', () => {
|
||||
const s = fresh()
|
||||
const tank = makeEnemy(s, 'tank', { x: CENTER.x + 400, y: CENTER.y })
|
||||
shot(s, CENTER.x + 400, CENTER.y, 8)
|
||||
step(s, [], 0.001)
|
||||
expect(tank.hp).toBe(112)
|
||||
expect(s.survivor.kills).toBe(0)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('a second projectile in the same tick passes through an already-dead target', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x + 400, y: CENTER.y })
|
||||
shot(s, CENTER.x + 400, CENTER.y, 20)
|
||||
shot(s, CENTER.x + 400, CENTER.y, 20)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(1)
|
||||
expect(s.projectiles).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('enemy fire hurts the survivor', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 500, from: 'enemy', pos: { x: CENTER.x, y: CENTER.y },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 7, ttl: 1,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
})
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.hp).toBe(93)
|
||||
expect(s.projectiles).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('enemy fire that misses keeps flying', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 501, from: 'enemy', pos: { x: 30, y: 30 },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 7, ttl: 1,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
})
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.hp).toBe(100)
|
||||
expect(s.projectiles).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('game end', () => {
|
||||
it('director wins when the survivor drops to zero', () => {
|
||||
const s = fresh()
|
||||
s.survivor.hp = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.status).toBe('directorWon')
|
||||
expect(s.outcomeTime).toBeCloseTo(0.01)
|
||||
})
|
||||
|
||||
it('survivor wins when the clock runs out', () => {
|
||||
const s = fresh(1, 0.05)
|
||||
step(s, [], 0.1)
|
||||
expect(s.status).toBe('survivorWon')
|
||||
})
|
||||
|
||||
it('a kill on the final tick still counts as a director win', () => {
|
||||
const s = fresh(1, 0.05)
|
||||
s.survivor.hp = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.1)
|
||||
expect(s.status).toBe('directorWon')
|
||||
})
|
||||
|
||||
it('a finished game is inert', () => {
|
||||
const s = fresh(1, 0.05)
|
||||
step(s, [], 0.1)
|
||||
const t = s.t
|
||||
step(s, [], 0.1)
|
||||
expect(s.t).toBe(t)
|
||||
})
|
||||
|
||||
it('director actions flow through step', () => {
|
||||
const s = fresh()
|
||||
step(s, [{ type: 'spawn', kind: 'rusher' }], 0.001)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
expect(s.director.energy).toBeLessThan(30)
|
||||
})
|
||||
})
|
||||
131
reverse_survivors/src/core/simFrenzy.test.ts
Normal file
131
reverse_survivors/src/core/simFrenzy.test.ts
Normal file
@ -0,0 +1,131 @@
|
||||
/** Frenzy, difficulty tiers and damage channels. */
|
||||
|
||||
/** Splitters, new units and status effects. */
|
||||
|
||||
/** Enemy behaviour, bombers and projectiles. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createInitialState, makeEnemy, step,
|
||||
} from './sim'
|
||||
import type { GameState, } from './types'
|
||||
import {
|
||||
ARENA, DIFFICULTIES, FRENZY_DAMAGE, FRENZY_SPEED, } from './types'
|
||||
|
||||
const CENTER = { x: ARENA.w / 2, y: ARENA.h / 2 }
|
||||
|
||||
const fresh = (seed = 1, duration?: number): GameState =>
|
||||
duration === undefined ? createInitialState(seed) : createInitialState(seed, duration)
|
||||
|
||||
|
||||
describe('frenzy', () => {
|
||||
it('speeds the horde while it lasts', () => {
|
||||
const base = fresh()
|
||||
const b = makeEnemy(base, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(base, [], 0.05)
|
||||
const normal = CENTER.x + 300 - b.pos.x
|
||||
|
||||
const hyped = fresh()
|
||||
hyped.director.frenzyTimer = 5
|
||||
const h = makeEnemy(hyped, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(hyped, [], 0.05)
|
||||
const rushed = CENTER.x + 300 - h.pos.x
|
||||
|
||||
expect(rushed).toBeCloseTo(normal * FRENZY_SPEED, 5)
|
||||
})
|
||||
|
||||
it('raises contact damage while it lasts', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBeCloseTo(100 - 6 * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('expires back to baseline speed', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 0.01
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.5)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
const after = e.pos.x
|
||||
step(s, [], 0.05)
|
||||
const moved = after - e.pos.x
|
||||
expect(moved).toBeCloseTo(170 * 0.05, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('difficulty tiers', () => {
|
||||
it('defaults to normal, the identity tier', () => {
|
||||
const s = fresh()
|
||||
expect(s.difficulty).toBe(DIFFICULTIES.normal)
|
||||
expect(s.survivor.maxHp).toBe(100)
|
||||
})
|
||||
|
||||
it('accepts an explicit tier', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
expect(s.difficulty).toBe(DIFFICULTIES.crusade)
|
||||
})
|
||||
|
||||
it('takes its duration from the tier when none is given', () => {
|
||||
expect(createInitialState(1, undefined, 'haunting').duration)
|
||||
.toBe(DIFFICULTIES.haunting.duration)
|
||||
})
|
||||
|
||||
it('an explicit duration still wins over the tier', () => {
|
||||
expect(createInitialState(1, 42, 'haunting').duration).toBe(42)
|
||||
})
|
||||
|
||||
it('scales enemy hp', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
const e = makeEnemy(s, 'rusher', { x: 0, y: 0 })
|
||||
expect(e.hp).toBeCloseTo(14 * DIFFICULTIES.crusade.enemyHp, 5)
|
||||
})
|
||||
|
||||
it('scales survivor hp', () => {
|
||||
const s = createInitialState(1, undefined, 'haunting')
|
||||
expect(s.survivor.maxHp).toBe(125)
|
||||
})
|
||||
|
||||
it('scales enemy speed', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
const moved = CENTER.x + 300 - e.pos.x
|
||||
expect(moved).toBeCloseTo(170 * DIFFICULTIES.crusade.enemySpeed * 0.05, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('frenzy damage reaches every channel', () => {
|
||||
// Regression: frenzy multiplied contact damage only, so ranged and blast
|
||||
// units — including the bomber, whose whole purpose is damage — ignored it.
|
||||
const dealt = (frenzied: boolean, kind: 'warden' | 'artillery' | 'bomber', at: number): number => {
|
||||
const s = fresh(3)
|
||||
s.survivor.hp = 1e6
|
||||
s.survivor.maxHp = 1e6
|
||||
s.survivor.speed = 0
|
||||
s.duration = 1e6
|
||||
if (frenzied) {
|
||||
s.director.frenzyTimer = 1e6
|
||||
}
|
||||
makeEnemy(s, kind, { x: CENTER.x + at, y: CENTER.y })
|
||||
const before = s.survivor.hp
|
||||
for (let i = 0; i < 360; i += 1) {
|
||||
step(s, [], 1 / 60)
|
||||
}
|
||||
return before - s.survivor.hp
|
||||
}
|
||||
|
||||
it('scales contact damage', () => {
|
||||
expect(dealt(true, 'warden', 0)).toBeCloseTo(dealt(false, 'warden', 0) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('scales ranged damage', () => {
|
||||
expect(dealt(true, 'artillery', 300))
|
||||
.toBeCloseTo(dealt(false, 'artillery', 300) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('scales blast damage', () => {
|
||||
expect(dealt(true, 'bomber', 0)).toBeCloseTo(dealt(false, 'bomber', 0) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
})
|
||||
243
reverse_survivors/src/core/simUnits.test.ts
Normal file
243
reverse_survivors/src/core/simUnits.test.ts
Normal file
@ -0,0 +1,243 @@
|
||||
/** Splitters, new units and status effects. */
|
||||
|
||||
/** Enemy behaviour, bombers and projectiles. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createInitialState, makeEnemy, SPLIT_RADIUS, step,
|
||||
} from './sim'
|
||||
import type { GameState, Projectile } from './types'
|
||||
import {
|
||||
ARENA, STATUS_POWER,
|
||||
} from './types'
|
||||
|
||||
const CENTER = { x: ARENA.w / 2, y: ARENA.h / 2 }
|
||||
|
||||
const fresh = (seed = 1, duration?: number): GameState =>
|
||||
duration === undefined ? createInitialState(seed) : createInitialState(seed, duration)
|
||||
|
||||
const shot = (state: GameState, x: number, y: number, damage: number): Projectile => {
|
||||
const p: Projectile = {
|
||||
id: state.nextId,
|
||||
from: 'survivor',
|
||||
pos: { x, y },
|
||||
vel: { x: 0, y: 0 },
|
||||
radius: 4,
|
||||
damage,
|
||||
ttl: 1,
|
||||
debuff: 'slow',
|
||||
debuffDuration: 0,
|
||||
}
|
||||
state.nextId += 1
|
||||
state.projectiles.push(p)
|
||||
return p
|
||||
}
|
||||
|
||||
describe('splitter', () => {
|
||||
it('dies into three rushers at fixed offsets', () => {
|
||||
const s = fresh()
|
||||
const sp = makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
const children = s.enemies.filter((e) => e.id !== sp.id)
|
||||
expect(children).toHaveLength(3)
|
||||
expect(children.every((c) => c.kind === 'rusher')).toBe(true)
|
||||
// Children drift toward the survivor within the same tick, so assert the
|
||||
// spawn ring loosely — the exact geometry is pinned by the test below.
|
||||
for (const c of children) {
|
||||
expect(Math.hypot(c.pos.x - 300, c.pos.y - 300)).toBeLessThan(SPLIT_RADIUS + 5)
|
||||
}
|
||||
})
|
||||
|
||||
it('spawns children on a ring at 120-degree offsets', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
// dt of 0 isolates the spawn geometry from the movement that follows it.
|
||||
step(s, [], 0)
|
||||
const angles = s.enemies
|
||||
.map((e) => Math.atan2(e.pos.y - 300, e.pos.x - 300))
|
||||
.sort((a, b) => a - b)
|
||||
expect(angles).toHaveLength(3)
|
||||
// Pairwise gaps without indexing (noUncheckedIndexedAccess would widen those).
|
||||
const gaps: number[] = []
|
||||
let prev: number | null = null
|
||||
for (const a of angles) {
|
||||
if (prev !== null) {
|
||||
gaps.push(a - prev)
|
||||
}
|
||||
prev = a
|
||||
}
|
||||
expect(gaps).toHaveLength(2)
|
||||
for (const g of gaps) {
|
||||
expect(g).toBeCloseTo((Math.PI * 2) / 3, 5)
|
||||
}
|
||||
})
|
||||
|
||||
it('children are deterministic and draw no RNG', () => {
|
||||
const run = (): { x: number; y: number }[] => {
|
||||
const s = fresh(42)
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
return s.enemies.map((e) => ({ x: e.pos.x, y: e.pos.y }))
|
||||
}
|
||||
expect(run()).toEqual(run())
|
||||
})
|
||||
|
||||
it('clamps children into the arena when it dies in a corner', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 2, y: 2 })
|
||||
shot(s, 2, 2, 999)
|
||||
step(s, [], 0.001)
|
||||
for (const e of s.enemies) {
|
||||
expect(e.pos.x).toBeGreaterThanOrEqual(10)
|
||||
expect(e.pos.y).toBeGreaterThanOrEqual(10)
|
||||
}
|
||||
})
|
||||
|
||||
it('a later projectile in the same tick can hit a fresh child', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
shot(s, 300 + SPLIT_RADIUS, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(2)
|
||||
})
|
||||
|
||||
it('non-splitting kinds spawn no children', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('new units', () => {
|
||||
it('artillery outranges the survivor and fires while it cannot', () => {
|
||||
const s = fresh()
|
||||
const a = makeEnemy(s, 'artillery', { x: CENTER.x + 400, y: CENTER.y })
|
||||
a.fireTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.projectiles.some((p) => p.from === 'enemy')).toBe(true)
|
||||
expect(s.projectiles.some((p) => p.from === 'survivor')).toBe(false)
|
||||
})
|
||||
|
||||
it('artillery holds station at its keep distance', () => {
|
||||
const s = fresh()
|
||||
const a = makeEnemy(s, 'artillery', { x: CENTER.x + 420, y: CENTER.y })
|
||||
const before = a.pos.x
|
||||
step(s, [], 0.016)
|
||||
expect(a.pos.x).toBeCloseTo(before, 5)
|
||||
})
|
||||
|
||||
it('warden closes faster than a rusher', () => {
|
||||
const s = fresh()
|
||||
const w = makeEnemy(s, 'warden', { x: CENTER.x + 300, y: CENTER.y })
|
||||
const r = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.016)
|
||||
expect(CENTER.x + 300 - w.pos.x).toBeGreaterThan(CENTER.x + 300 - r.pos.x)
|
||||
})
|
||||
|
||||
it('the hivemind still births rushers via spawnKind', () => {
|
||||
const s = fresh()
|
||||
const h = makeEnemy(s, 'hivemind', { x: 40, y: 40 })
|
||||
h.spawnTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.enemies.some((e) => e.kind === 'rusher')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('status effects', () => {
|
||||
it('a warden contact mires the survivor and halves its movement', () => {
|
||||
const slowed = fresh()
|
||||
slowed.survivor.pos = { x: 100, y: CENTER.y }
|
||||
makeEnemy(slowed, 'warden', { x: 100, y: CENTER.y })
|
||||
step(slowed, [], 0.01)
|
||||
// Statuses tick in survivorStep, which runs before enemiesStep applies
|
||||
// contact — so a status landing this tick starts at its full duration.
|
||||
expect(slowed.survivor.statuses.slow).toBe(2.0)
|
||||
|
||||
// Control: same displacement, an enemy that inflicts nothing.
|
||||
const control = fresh()
|
||||
control.survivor.pos = { x: 100, y: CENTER.y }
|
||||
makeEnemy(control, 'rusher', { x: 100, y: CENTER.y })
|
||||
step(control, [], 0.01)
|
||||
expect(control.survivor.statuses.slow).toBe(0)
|
||||
|
||||
const before = { slowed: slowed.survivor.pos.x, control: control.survivor.pos.x }
|
||||
slowed.enemies = []
|
||||
control.enemies = []
|
||||
step(slowed, [], 0.05)
|
||||
step(control, [], 0.05)
|
||||
const movedSlowed = slowed.survivor.pos.x - before.slowed
|
||||
const movedControl = control.survivor.pos.x - before.control
|
||||
expect(movedSlowed).toBeCloseTo(movedControl * STATUS_POWER.slow, 5)
|
||||
})
|
||||
|
||||
it('slow expires and full speed returns', () => {
|
||||
const s = fresh()
|
||||
s.survivor.pos = { x: 100, y: CENTER.y }
|
||||
s.survivor.statuses.slow = 0.02
|
||||
step(s, [], 0.05)
|
||||
expect(s.survivor.statuses.slow).toBe(0)
|
||||
})
|
||||
|
||||
it('an artillery shell stifles the survivor and lengthens its reload', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 900, from: 'enemy', pos: { x: CENTER.x, y: CENTER.y },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 13, ttl: 1,
|
||||
debuff: 'suppress', debuffDuration: 2.5,
|
||||
})
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 200, y: CENTER.y })
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.statuses.suppress).toBeGreaterThan(0)
|
||||
// The shot fired this tick reloaded before the status landed; the next one pays.
|
||||
s.survivor.fireTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.fireTimer).toBeCloseTo(0.55 * STATUS_POWER.suppress, 5)
|
||||
})
|
||||
|
||||
it('a leech contact blocks regeneration until it expires', () => {
|
||||
const s = fresh()
|
||||
s.survivor.regen = 5
|
||||
s.survivor.hp = 50
|
||||
makeEnemy(s, 'leech', { x: CENTER.x, y: CENTER.y })
|
||||
const hp0 = s.survivor.hp
|
||||
step(s, [], 0.1)
|
||||
// Contact damage lands and regen is suppressed, so hp cannot have risen.
|
||||
expect(s.survivor.hp).toBeLessThan(hp0)
|
||||
expect(s.survivor.statuses.bleed).toBeGreaterThan(0)
|
||||
|
||||
s.enemies = []
|
||||
s.survivor.statuses.bleed = 0
|
||||
const hp1 = s.survivor.hp
|
||||
step(s, [], 0.1)
|
||||
expect(s.survivor.hp).toBeGreaterThan(hp1)
|
||||
})
|
||||
|
||||
it('repeated warden contacts refresh rather than stack', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'warden', { x: CENTER.x, y: CENTER.y })
|
||||
makeEnemy(s, 'warden', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.statuses.slow).toBeLessThanOrEqual(2.0)
|
||||
})
|
||||
|
||||
it('a plain rusher inflicts no status at all', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.statuses).toEqual({ slow: 0, suppress: 0, bleed: 0 })
|
||||
})
|
||||
|
||||
it('survivor fire never debuffs the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 200, y: CENTER.y })
|
||||
step(s, [], 0.001)
|
||||
const own = s.projectiles.find((p) => p.from === 'survivor')
|
||||
expect(own?.debuffDuration).toBe(0)
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue
Block a user