#!/usr/bin/env bash
# FAULT: Tachyon rewrites flash with byte-identical content, over and over.
#
# On a router the flash is the only component that actually dies. NAND wears out
# long before the CPU does, and almost everything Tachyon regenerates is derived
# data that comes back identical most of the time: the per-channel
# domain lists, the zapret opts files, the compiled .srs rulesets, the
# subscription cache, the tachyon-core config.
#
# Measured on 192.168.1.1: one list update rewrote all 33 .srs rulesets - 2.5 MB
# - inside four minutes, with identical content, because the copy was
# unconditional. Nothing about that shows up in the UI, and the router just gets a
# little more worn out every time.
#
# The three central writers in core/common.uc - write_file, write_json_file and
# copy_file - are where every regenerator funnels through, so the guard belongs
# there rather than at the ~230 call sites.
. "$(dirname "${BASH_SOURCE[0]}")/lib/harness.sh"
set -eo pipefail

LIB_DIR="${TACHYON_LIB:-$ROOT_DIR/tachyon/files/usr/lib}"

[ -f "$LIB_DIR/core/common.uc" ] || fail "core/common.uc not found"

trap 'rm -rf "$WORK_DIR"' EXIT

# Writes the same content twice and reports whether the second write actually
# touched the file, by comparing the inode's mtime with a sleep in between.
# mtime resolution on a router filesystem is 1s, so the sleep has to clear it.
probe_unchanged_write() {
  ucode -L "$LIB_DIR" -e '
let fs = require("fs");
let common = require("core.common");
let path = getenv("PROBE_PATH");
let value = getenv("PROBE_VALUE");
common.write_file(path, value);
system("sleep 1.1");
let before = fs.stat(path).mtime;
common.write_file(path, value);
system("sleep 1.1");
let after = fs.stat(path).mtime;
printf("unchanged_skipped=%s\n", after == before ? "yes" : "no");
' 2>&1
}

probe_changed_write() {
  ucode -L "$LIB_DIR" -e '
let fs = require("fs");
let common = require("core.common");
let path = getenv("PROBE_PATH");
common.write_file(path, "first\n");
system("sleep 1.1");
let before = fs.stat(path).mtime;
common.write_file(path, "second and different\n");
let after = fs.stat(path).mtime;
printf("changed_written=%s content=%s\n",
  after != before ? "yes" : "no",
  join("", [ fs.readfile(path) == "second and different\n" ? "ok" : "WRONG" ]));
' 2>&1
}

probe_json_unchanged() {
  ucode -L "$LIB_DIR" -e '
let fs = require("fs");
let common = require("core.common");
let path = getenv("PROBE_PATH");
let spec = { outputs: { "direct": { kind: "direct" } }, channels: [ { name: "a" } ] };
common.write_json_file(path, spec);
system("sleep 1.1");
let before = fs.stat(path).mtime;
common.write_json_file(path, spec);
system("sleep 1.1");
let after = fs.stat(path).mtime;
printf("json_unchanged_skipped=%s\n", after == before ? "yes" : "no");
' 2>&1
}

probe_copy_unchanged() {
  ucode -L "$LIB_DIR" -e '
let fs = require("fs");
let common = require("core.common");
let src = getenv("PROBE_SRC");
let dst = getenv("PROBE_DST");
common.write_file(src, "compiled ruleset bytes\n");
common.copy_file(src, dst);
system("sleep 1.1");
let before = fs.stat(dst).mtime;
common.copy_file(src, dst);
system("sleep 1.1");
let after = fs.stat(dst).mtime;
printf("copy_unchanged_skipped=%s\n", after == before ? "yes" : "no");
' 2>&1
}

# --- write_file: identical content must not be written again ------------------
out="$(PROBE_PATH="$WORK_DIR/plain.txt" PROBE_VALUE="regenerated content\n" probe_unchanged_write)" ||
  fail "could not drive write_file: $out"
grep -q 'unchanged_skipped=yes' <<< "$out" ||
  fail "write_file rewrote a file with identical content, so every regeneration costs a flash update whether or not anything changed: $out"

# --- write_file: real changes must still land --------------------------------
# A guard that skipped everything would be worse than no guard at all: the
# regenerated spec would never reach disk and the engine would keep running the
# old rules.
out="$(PROBE_PATH="$WORK_DIR/changing.txt" probe_changed_write)" ||
  fail "could not drive the changed-content write: $out"
grep -q 'changed_written=yes' <<< "$out" ||
  fail "write_file skipped a genuine content change, so config changes would never reach the engine: $out"
grep -q 'content=ok' <<< "$out" ||
  fail "write_file did not persist the new content: $out"

# --- write_json_file: same, and it must not leave temp files behind ---------
out="$(PROBE_PATH="$WORK_DIR/spec.json" probe_json_unchanged)" ||
  fail "could not drive write_json_file: $out"
grep -q 'json_unchanged_skipped=yes' <<< "$out" ||
  fail "write_json_file rewrote an identical JSON file, burning a tmp write plus a rename on flash every time the spec is regenerated: $out"

leftover="$(find "$WORK_DIR" -name '*.tmp' | wc -l)"
[ "$leftover" -eq 0 ] || fail "write_json_file left $leftover temp file(s) behind: $(find "$WORK_DIR" -name '*.tmp')"

# --- copy_file: this is the one that rewrote 2.5 MB of rulesets ------------
out="$(PROBE_SRC="$WORK_DIR/ruleset.srs" PROBE_DST="$WORK_DIR/persistent.srs" probe_copy_unchanged)" ||
  fail "could not drive copy_file: $out"
grep -q 'copy_unchanged_skipped=yes' <<< "$out" ||
  fail "copy_file rewrote an identical ruleset, which is how a single list update put 2.5 MB through the flash on a router: $out"

# --- a different size must not be mistaken for unchanged --------------------
# Size is compared before content as a fast path, so a same-size but different
# payload has to be caught by the content compare rather than skipped.
out="$(PROBE_PATH="$WORK_DIR/probe.bin" ucode -L "$LIB_DIR" -e '
let fs = require("fs");
let common = require("core.common");
let path = getenv("PROBE_PATH");
// A null path makes every assertion below vacuously true, which is how a test
// ends up passing without testing anything. Fail loudly instead.
if (path == null || path == "") {
  print("PROBE_PATH is not set - refusing to run a vacuous check");
  exit(1);
}
common.write_file(path, "AAAA\n");
let same_size = common.content_unchanged(path, "BBBB\n");
let different_size = common.content_unchanged(path, "CCCCC\n");
let identical = common.content_unchanged(path, "AAAA\n");
let missing = common.content_unchanged("/nonexistent/nope", "x\n");
printf("same_size_changed=%s different_size_changed=%s identical=%s missing=%s\n",
  same_size ? "no" : "yes",
  different_size ? "no" : "yes",
  identical ? "yes" : "no",
  missing ? "no" : "yes");
' 2>&1)" || fail "could not drive content_unchanged: $out"

grep -q 'same_size_changed=yes' <<< "$out" ||
  fail "a same-size but different payload was treated as unchanged, so real config changes would be silently dropped: $out"
grep -q 'different_size_changed=yes' <<< "$out" ||
  fail "a different-size payload was treated as unchanged: $out"
grep -q 'identical=yes' <<< "$out" ||
  fail "identical content was not recognised, so the guard never fires: $out"
grep -q 'missing=yes' <<< "$out" ||
  fail "a missing file was treated as unchanged, so the first write of every file would be skipped: $out"

# The library must be requireable without running a CLI or exiting, while the CLI
# shim must still work as a program. These used to be one file, which is exactly
# why it could not do both.
ucode -L "$LIB_DIR" "$LIB_DIR/service/engine_runtime.uc" engine-info >/dev/null 2>&1 \
  || fail "the engine_runtime CLI shim no longer answers engine-info"
out="$(ucode -L "$LIB_DIR" -e 'let rt = require("service.engine_runtime_lib"); print("lib=" + (type(rt.start_active) == "function" ? "yes" : "no") + "\n");' with-an-argument 2>&1)" \
  || fail "requiring the library with an argument must not run a CLI or exit: $out"
grep -q '^lib=yes$' <<< "$out" || fail "the library exports nothing usable: $out"

# Production code requires the library; pointing it back at the CLI shim would run
# main() with the caller's arguments and exit the interpreter underneath them.
for caller in "$LIB_DIR/components/action.uc" "$LIB_DIR/diagnostics/system_info.uc"; do
  if grep -q 'require("service.engine_runtime")' "$caller"; then
    fail "$caller still requires the CLI shim, which runs main() and exits on import"
  fi
done

# Module-local write_file helpers in runtime/subscription must delegate to
# common.write_file so flash files (/etc/tachyon/*) never bypass content_unchanged.
for mod in "$LIB_DIR/tachyon_core/runtime.uc" "$LIB_DIR/subscription/cache.uc"; do
  fn_body="$(sed -n '/^function write_file(/,/^}/p' "$mod")"
  grep -Fq 'common.write_file' <<< "$fn_body" ||
    fail "$mod write_file() bypassed common.write_file: $fn_body"
done

# Repeatedly persisting an unchanged subscription cache must not touch mtime or
# ctime (no redundant chmod/rewrite on /etc/tachyon/subscription-cache).
mkdir -p "$WORK_DIR/sub-run" "$WORK_DIR/sub-persist"
cat >"$WORK_DIR/sub-run/src.json" <<'JSON'
{"outbounds":[{"type":"direct","tag":"one"}]}
JSON
cat >"$WORK_DIR/sub-run/meta.json" <<'JSON'
{"version":1,"title":"Test"}
JSON
TACHYON_PERSISTENT_SUBSCRIPTION_CACHE_DIR="$WORK_DIR/sub-persist" \
  TMP_SUBSCRIPTION_FOLDER="$WORK_DIR/sub-run" \
  TACHYON_SUBSCRIPTION_METADATA_DIR="$WORK_DIR/sub-run/meta" \
  ucode -L "$LIB_DIR" "$LIB_DIR/subscription/cache.uc" persist-source-cache \
    proxy-subscription-1 "$WORK_DIR/sub-run/src.json" "https://example.com/sub" "v2rayN" "$WORK_DIR/sub-run/meta.json"
sleep 1.1
ctime_before="$(stat -c '%Y:%Z' "$WORK_DIR/sub-persist/proxy-subscription-1.json" "$WORK_DIR/sub-persist/proxy-subscription-1.url")"
TACHYON_PERSISTENT_SUBSCRIPTION_CACHE_DIR="$WORK_DIR/sub-persist" \
  TMP_SUBSCRIPTION_FOLDER="$WORK_DIR/sub-run" \
  TACHYON_SUBSCRIPTION_METADATA_DIR="$WORK_DIR/sub-run/meta" \
  ucode -L "$LIB_DIR" "$LIB_DIR/subscription/cache.uc" persist-source-cache \
    proxy-subscription-1 "$WORK_DIR/sub-run/src.json" "https://example.com/sub" "v2rayN" "$WORK_DIR/sub-run/meta.json"
sleep 1.1
ctime_after="$(stat -c '%Y:%Z' "$WORK_DIR/sub-persist/proxy-subscription-1.json" "$WORK_DIR/sub-persist/proxy-subscription-1.url")"
[ "$ctime_before" = "$ctime_after" ] ||
  fail "persist-source-cache modified mtime/ctime on unchanged subscription cache ($ctime_before -> $ctime_after)"

printf 'fault: flash wear guard passed\n'
