# CH-J Server Manager - fixed remote helper for swap inspection and management (POSIX sh).
# Started by Core as "sh -c SCRIPT chj OPERATION ARGS..." (through sudo/root for changes). Arguments are
# validated by Core and again here. Changes are never made from the monitoring loop.
set -u
umask 077
LC_ALL=C; export LC_ALL
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; export PATH
FSTAB=/etc/fstab
MARK='# CH-J chj.system-monitor'
LOCK=/run/chj-swap.lock
# Overridable only for the unit tests (fake /proc and fstab; nothing on the host is touched).
PROC=${CHJ_SWAP_TEST_PROC:-/proc}
[ -n "${CHJ_SWAP_TEST_PROC:-}" ] && FSTAB=${CHJ_SWAP_TEST_FSTAB:-$FSTAB}
op=${1:-}
[ $# -gt 0 ] && shift
printf '\036CHJ_READY\n'

fail() { printf '\036CHJ_ERR=%s\n' "$1"; [ $# -gt 1 ] && printf '%s\n' "$2" | head -c 2000 >&2; exit 3; }
have() { command -v "$1" >/dev/null 2>&1; }
is_root() { [ "$(id -u)" = 0 ]; }
need_root() { is_root || fail PRIVILEGE_REQUIRED "Root privileges are required."; }
# Swap files may live only at /swapfile*, /swap/<name> or /var/lib/swap/<name>.
managed_path() {
  case $1 in
    /swapfile|/swapfile[A-Za-z0-9._-]*|/swap/[A-Za-z0-9._-]*|/var/lib/swap/[A-Za-z0-9._-]*) ;;
    *) return 1 ;;
  esac
  case $1 in *..*|*/./*|*//*) return 1 ;; esac
  [ ${#1} -le 96 ]
}
safe_path() { case $1 in /*) ;; *) return 1 ;; esac; case $1 in *[!A-Za-z0-9._/-]*|*..*) return 1 ;; esac; [ ${#1} -le 200 ]; }
valid_int() { case $1 in ''|*[!0-9]*) return 1 ;; esac; [ ${#1} -le 9 ]; }
# Priority on the wire: -1 = automatic (kernel assigns decreasing negative values), 0-32767 = explicit
# (swapon(2) SWAP_FLAG_PREFER range), keep = reuse the configured/explicit priority of the area.
valid_prio() { case $1 in -1|keep) return 0 ;; ''|*[!0-9]*) return 1 ;; esac; [ ${#1} -le 5 ] && [ "$1" -le 32767 ]; }
meminfo() { awk -v key="$1" '$1==key":" { print $2*1024; found=1 } END { if (!found) print 0 }' "$PROC/meminfo"; }
active_line() { awk -v p="$1" 'NR>1 && $1==p { print; exit }' "$PROC/swaps"; }
runtime_prio() { active_line "$1" | awk '{ print $5 }'; }
is_active() { [ -n "$(active_line "$1")" ]; }
used_of() { active_line "$1" | awk '{ printf "%.0f", $4*1024 }'; }
is_swap_signature() {
  page=$(getconf PAGESIZE 2>/dev/null || echo 4096)
  [ "$(dd if="$1" bs=1 skip=$((page - 10)) count=10 2>/dev/null)" = SWAPSPACE2 ]
}
# Mount table first: statfs reports ext4 as "ext2/ext3". The longest mount point containing $1 wins.
fs_type() {
  t=$(findmnt -no FSTYPE -T "$1" 2>/dev/null)
  [ -n "$t" ] || t=$(awk -v p="$1" '{ m=$2; if (m=="/" || p==m || index(p, m "/")==1) if (length(m)>=best) { best=length(m); fs=$3 } } END { if (fs!="") print fs }' "$PROC/mounts" 2>/dev/null)
  [ -n "$t" ] || t=$(stat -f -c %T "$1" 2>/dev/null)
  printf '%s\n' "${t:-unknown}"
}

lock() {
  mkdir "$LOCK" 2>/dev/null || fail SWAP_BUSY "Another swap operation is running on this server."
  trap 'rmdir "$LOCK" 2>/dev/null' EXIT INT TERM
}

# swapoff only when the pages can move to RAM (keeping a reserve) or to other active swap.
assert_swapoff_safe() {
  target=$1
  used=$(used_of "$target"); [ -n "$used" ] || used=0
  [ "$used" -gt 0 ] || return 0
  available=$(meminfo MemAvailable); total=$(meminfo MemTotal)
  # Reserve: 10 % of RAM, at least 512 MiB, but never more than a quarter of RAM (small servers).
  reserve=$((total / 10)); [ "$reserve" -ge 536870912 ] || reserve=536870912
  [ "$reserve" -le $((total / 4)) ] || reserve=$((total / 4))
  other_free=$(awk -v p="$target" 'NR>1 && $1!=p { free += ($3-$4)*1024 } END { printf "%.0f", free+0 }' "$PROC/swaps")
  room=$((available - reserve + other_free))
  if [ "$used" -gt "$room" ]; then
    fail SWAPOFF_UNSAFE "Deactivating $target would move $((used / 1048576)) MiB into memory, but only $((room / 1048576)) MiB can be absorbed safely (MemAvailable minus a reserve of $((reserve / 1048576)) MiB plus free space in other swap areas)."
  fi
}

# Canonical identity of an fstab/proc swap spec: path, /dev node, UUID=, LABEL=, PARTUUID= or PARTLABEL=.
canon() {
  if [ -n "${CHJ_SWAP_TEST_PROC:-}" ] && [ -r "$PROC/canon" ]; then
    hit=$(awk -F'|' -v s="$1" '$1==s { print $2; exit }' "$PROC/canon"); [ -n "$hit" ] && { printf '%s\n' "$hit"; return; }
  fi
  case $1 in
    UUID=*|LABEL=*|PARTUUID=*|PARTLABEL=*)
      key=${1%%=*}; val=${1#*=}; val=${val#\"}; val=${val%\"}
      dev=$(findfs "$key=$val" 2>/dev/null) || dev=""
      if [ -z "$dev" ]; then
        dir=$(printf '%s' "$key" | tr 'A-Z' 'a-z')
        [ -e "/dev/disk/by-$dir/$val" ] && dev=$(readlink -f "/dev/disk/by-$dir/$val" 2>/dev/null)
      fi
      printf '%s\n' "${dev:-$1}" ;;
    /*) [ -e "$1" ] && readlink -f "$1" 2>/dev/null || printf '%s\n' "$1" ;;
    *) printf '%s\n' "$1" ;;
  esac
}
# Line numbers of active (uncommented) fstab swap entries that identify the same swap space as $1.
fstab_matches() {
  [ -r "$FSTAB" ] || return 0
  want=$(canon "$1")
  awk '!/^[[:space:]]*#/ && $3=="swap" { print NR "|" $1 }' "$FSTAB" | while IFS='|' read -r n spec; do
    if [ "$spec" = "$1" ] || [ "$(canon "$spec")" = "$want" ]; then printf '%s\n' "$n"; fi
  done
}
fstab_entry() { fstab_matches "$1" | head -n 1; }
# Must run in the main shell (not inside $(...)), otherwise fail could not stop the script.
fstab_check() {
  m=$(fstab_matches "$1")
  [ "$(printf '%s\n' "$m" | grep -c .)" -le 1 ] || fail FSTAB_AMBIGUOUS "/etc/fstab contains several active swap entries for $1 (lines $(printf '%s' "$m" | tr '\n' ' ')); resolve them manually first."
}
fstab_pri() {
  n=$(fstab_entry "$1"); [ -n "$n" ] || return 0
  awk -v n="$n" 'NR==n+0 { k=split($4, o, ","); for (i=1;i<=k;i++) if (o[i] ~ /^pri=[0-9]+$/) print substr(o[i],5) }' "$FSTAB" | tail -n 1
}
# keep -> priority from fstab, else the current explicit runtime priority, else automatic.
resolve_prio() {
  [ "$2" = keep ] || { printf '%s\n' "$2"; return; }
  p=$(fstab_pri "$1"); [ -n "$p" ] && { printf '%s\n' "$p"; return; }
  p=$(runtime_prio "$1"); case $p in ''|-*) printf '%s\n' -1 ;; *) printf '%s\n' "$p" ;; esac
}
# fstab_apply PATH MODE PRIO, MODE: persist (keep/update an existing entry or append one), priority (update an
# existing entry only), remove. PRIO: -1 removes pri=, 0-32767 sets it, keep leaves the options untouched.
# The matching line keeps its spec, other options, dump/pass fields and comment; all other lines stay byte-identical.
fstab_apply() {
  path=$1; mode=$2; prio=$3
  [ -f "$FSTAB" ] || fail FSTAB_MISSING "/etc/fstab does not exist."
  [ ! -L "$FSTAB" ] || fail FSTAB_UNSAFE "/etc/fstab is a symbolic link."
  fstab_check "$path"; n=$(fstab_entry "$path")
  case $mode in priority|remove) [ -n "$n" ] || return 0 ;; esac
  stamp=$(date -u +%Y%m%dT%H%M%SZ)
  # Unique name: several changes within one second must not overwrite the earlier original.
  LAST_BACKUP=$(mktemp "$FSTAB.chj-backup-$stamp-XXXXXX" 2>/dev/null) && cp -p "$FSTAB" "$LAST_BACKUP" || { [ -n "${LAST_BACKUP:-}" ] && rm -f "$LAST_BACKUP"; fail FSTAB_BACKUP_FAILED "The /etc/fstab backup could not be created."; }
  tmp=$(mktemp "$FSTAB.chj-XXXXXX") || fail FSTAB_WRITE_FAILED "Temporary file failed."
  awk -v n="$n" -v mode="$mode" -v prio="$prio" -v p="$path" -v mark="$MARK" '
    function setpri(opts,   k, i, o, out) {
      if (prio == "keep") return opts
      k = split(opts, o, ","); out = ""
      for (i = 1; i <= k; i++) if (o[i] != "" && o[i] !~ /^pri=/) out = out (out == "" ? "" : ",") o[i]
      if (prio ~ /^[0-9]+$/) out = out (out == "" ? "" : ",") "pri=" prio
      return out == "" ? "defaults" : out
    }
    n != "" && NR == n + 0 {
      if (mode == "remove") next
      c = index($0, "#"); comment = c ? substr($0, c) : ""; body = c ? substr($0, 1, c - 1) : $0
      nf = split(body, f, /[ \t]+/); if (f[1] == "") { for (i = 1; i < nf; i++) f[i] = f[i + 1]; nf-- }
      if (f[nf] == "") nf--
      if (nf < 4) { f[4] = "sw"; nf = 4 }
      f[4] = setpri(f[4]); line = f[1]; for (i = 2; i <= nf; i++) line = line " " f[i]
      print line (comment != "" ? " " comment : ""); next
    }
    { print }
    END { if (mode == "persist" && n == "") printf "%s none swap %s 0 0 %s\n", p, setpri("sw"), mark }' "$FSTAB" > "$tmp" || { rm -f "$tmp"; fail FSTAB_WRITE_FAILED "fstab could not be rewritten."; }
  chmod --reference="$FSTAB" "$tmp" 2>/dev/null || chmod 644 "$tmp"
  chown --reference="$FSTAB" "$tmp" 2>/dev/null || chown 0:0 "$tmp" 2>/dev/null
  mv -f "$tmp" "$FSTAB" || { rm -f "$tmp"; fail FSTAB_WRITE_FAILED "fstab could not be replaced."; }
  ls -1t "$FSTAB".chj-backup-* 2>/dev/null | tail -n +11 | while IFS= read -r old; do rm -f -- "$old"; done
  if [ -z "${CHJ_SWAP_TEST_PROC:-}" ] && have systemctl && [ -d /run/systemd/system ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi
  printf '\036CHJ_STEP=fstab|ok|backup %s\n' "$LAST_BACKUP"
}
# Puts the pre-change fstab back (atomically) after a failed runtime step.
fstab_restore() {
  [ -n "${LAST_BACKUP:-}" ] && [ -f "$LAST_BACKUP" ] || return 0
  tmp=$(mktemp "$FSTAB.chj-XXXXXX") && cp -p "$LAST_BACKUP" "$tmp" && mv -f "$tmp" "$FSTAB" && printf '\036CHJ_STEP=fstab|restored|%s\n' "$LAST_BACKUP"
}

# Builds a valid swap file at $1 with $2 MiB, honouring file system rules (Btrfs: NOCOW, no holes on XFS/ext4).
build_swapfile() {
  target=$1; size=$2
  dir=${target%/*}; [ -n "$dir" ] || dir=/
  fstype=$(fs_type "$dir")
  case $fstype in
    ext2/ext3|ext4|ext2|ext3|xfs|btrfs|f2fs) ;;
    *) fail SWAP_FS_UNSUPPORTED "Swap files are not supported safely on the $fstype file system." ;;
  esac
  free=$(df -PB1 "$dir" | awk 'NR==2 { print $4 }')
  need=$((size * 1048576 + 1073741824))
  [ "$free" -ge "$need" ] || fail SWAP_DISK_FULL "Not enough free space in $dir: $((free / 1048576)) MiB free, $((need / 1048576)) MiB needed including a 1 GiB reserve."
  tmp="$dir/.${target##*/}.chj-new"
  rm -f -- "$tmp"
  if [ "$fstype" = btrfs ]; then
    if have btrfs && btrfs filesystem mkswapfile --help >/dev/null 2>&1; then
      out=$(btrfs filesystem mkswapfile --size "${size}m" "$tmp" 2>&1) || { rm -f -- "$tmp"; fail SWAP_BTRFS_FAILED "$out"; }
    else
      : > "$tmp" && chattr +C "$tmp" 2>/dev/null || { rm -f -- "$tmp"; fail SWAP_BTRFS_NOCOW "The NOCOW attribute could not be set (chattr +C); Btrfs swap files need it."; }
      dd if=/dev/zero of="$tmp" bs=1M count="$size" status=none conv=fsync || { rm -f -- "$tmp"; fail SWAP_WRITE_FAILED "Writing the swap file failed."; }
      chmod 600 "$tmp"; out=$(mkswap "$tmp" 2>&1) || { rm -f -- "$tmp"; fail SWAP_MKSWAP_FAILED "$out"; }
    fi
  else
    # dd writes every block: fallocate/truncate can leave unwritten extents that swapon rejects (e.g. XFS).
    dd if=/dev/zero of="$tmp" bs=1M count="$size" status=none conv=fsync || { rm -f -- "$tmp"; fail SWAP_WRITE_FAILED "Writing the swap file failed (disk full?)."; }
    chmod 600 "$tmp"; out=$(mkswap "$tmp" 2>&1) || { rm -f -- "$tmp"; fail SWAP_MKSWAP_FAILED "$out"; }
  fi
  chown 0:0 "$tmp"; chmod 600 "$tmp"
  mv -f -- "$tmp" "$target" || { rm -f -- "$tmp"; fail SWAP_WRITE_FAILED "The swap file could not be moved into place."; }
  if have restorecon; then restorecon "$target" >/dev/null 2>&1 || true; fi
}

try_swapon() {
  case $2 in -*|'') out=$(swapon "$1" 2>&1) ;; *) out=$(swapon -p "$2" "$1" 2>&1) ;; esac
}
activate() { try_swapon "$1" "$2" || fail SWAPON_FAILED "swapon $1 failed: $out"; }
# Applies a priority to a running swap area. The kernel cannot change the priority of an active area, so it is
# swapped off and on again; on any failure the previous priority (and fstab) is restored, never left inactive.
reprioritize() {
  target=$1; want=$2; old=$(runtime_prio "$target")
  out=$(swapoff "$target" 2>&1) || { fstab_restore; fail SWAPOFF_FAILED "$out"; }
  if ! try_swapon "$target" "$want"; then
    reason=$out
    case $old in -*|'') swapon "$target" >/dev/null 2>&1 ;; *) swapon -p "$old" "$target" >/dev/null 2>&1 ;; esac
    fstab_restore
    fail SWAPON_FAILED "swapon with priority $want failed ($reason); the swap area was reactivated with its previous priority and /etc/fstab was restored."
  fi
}

status() {
  printf '\036CHJ_SECTION=swaps\n'; cat /proc/swaps
  printf '\036CHJ_SECTION=meminfo\n'; grep -E '^(MemTotal|MemAvailable|SwapTotal|SwapFree):' /proc/meminfo
}

op_inspect() {
  printf '\036CHJ_SECTION=meta\n'
  printf 'root=%s\n' "$(is_root && echo 1 || echo 0)"
  printf 'systemd=%s\n' "$( (have systemctl && [ -d /run/systemd/system ]) && echo 1 || echo 0)"
  printf 'btrfsMkswapfile=%s\n' "$( (have btrfs && btrfs filesystem mkswapfile --help >/dev/null 2>&1) && echo 1 || echo 0)"
  printf 'os=%s\n' "$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | head -n 1 | tr -d '"')"
  status
  printf '\036CHJ_SECTION=fstab\n'
  # line|canonical device or path|raw line (the canonical identity matches UUID=/LABEL= entries to /proc/swaps).
  [ -r "$FSTAB" ] && awk '$3=="swap" || /^[^#]*[[:space:]]swap[[:space:]]/ { print NR "|" $1 "|" $0 }' "$FSTAB" | while IFS='|' read -r n spec raw; do
    printf '%s|%s|%s\n' "$n" "$(canon "$spec")" "$raw"
  done
  printf '\036CHJ_SECTION=units\n'
  if have systemctl && [ -d /run/systemd/system ]; then
    systemctl list-units --type=swap --all --no-legend --plain 2>/dev/null | awk '{ print $1 "|" $3 "|" $4 }' | head -n 32
  fi
  printf '\036CHJ_SECTION=files\n'
  listed=" $(awk 'NR>1 { printf "%s ", $1 }' /proc/swaps) $( [ -r "$FSTAB" ] && awk '$3=="swap" && $1 ~ /^\// { printf "%s ", $1 }' "$FSTAB") "
  for path in $listed /swapfile /swapfile* /swap/* /var/lib/swap/*; do
    [ -e "$path" ] || continue
    # Directory candidates count only when they are regular files carrying the swap signature.
    case $listed in *" $path "*) ;; *) [ -f "$path" ] && [ ! -L "$path" ] && is_swap_signature "$path" || continue ;; esac
    case $path in /dev/*) kind=partition; [ "${path#/dev/zram}" != "$path" ] && kind=zram ;; *) kind=file ;; esac
    if [ "$kind" = file ]; then
      printf '%s|%s|%s|%s|%s|%s\n' "$path" "$kind" "$(fs_type "${path%/*}/")" "$(stat -c '%s|%U|%a' "$path" 2>/dev/null)" "$(managed_path "$path" && echo managed || echo foreign)" "$(df -PB1 "${path%/*}/" 2>/dev/null | awk 'NR==2 { print $4 }')"
    else
      printf '%s|%s|-|%s|0|-|foreign|-\n' "$path" "$kind" "$(blockdev --getsize64 "$path" 2>/dev/null || echo 0)"
    fi
  done | awk -F'|' '!seen[$1]++'
  printf '\036CHJ_SECTION=locations\n'
  for dir in / /swap /var/lib/swap; do
    [ -d "$dir" ] || continue
    printf '%s|%s|%s\n' "$dir" "$(fs_type "$dir")" "$(df -PB1 "$dir" 2>/dev/null | awk 'NR==2 { print $4 }')"
  done
  printf '\036CHJ_SECTION=zram\n'
  for zram in /sys/block/zram*; do [ -r "$zram/mm_stat" ] && printf '%s|%s|%s\n' "$(basename "$zram")" "$(cat "$zram/disksize")" "$(tr -s ' ' ',' < "$zram/mm_stat")"; done
  printf '\036CHJ_SECTION=end\n'
}

op_manage() {
  [ $# -eq 5 ] || [ $# -eq 6 ] || fail ARGUMENTS_INVALID "Invalid arguments."
  action=$1; path=$2; size=$3; prio=$4; persist=$5; apply=${6:-now}
  need_root
  safe_path "$path" || fail SWAP_PATH_INVALID "Invalid swap path."
  valid_int "$size" && valid_prio "$prio" || fail ARGUMENTS_INVALID "Invalid size or priority."
  case $persist in 0|1|keep) ;; *) fail ARGUMENTS_INVALID "Invalid persistence flag." ;; esac
  case $apply in now|later) ;; *) fail ARGUMENTS_INVALID "Invalid apply mode." ;; esac
  lock
  [ -r "$FSTAB" ] && fstab_check "$path"
  case $path in /dev/zram*) fail SWAP_ZRAM_READ_ONLY "zram is shown read-only; CH-J does not configure it." ;; esac
  case $action in
    create)
      [ "$prio" != keep ] || fail ARGUMENTS_INVALID "A new swap file needs automatic or explicit priority."
      managed_path "$path" || fail SWAP_PATH_INVALID "New swap files may be created only as /swapfile*, /swap/<name> or /var/lib/swap/<name>."
      [ ! -e "$path" ] || fail SWAP_EXISTS "The file already exists."
      [ "$size" -ge 64 ] && [ "$size" -le 65536 ] || fail SWAP_SIZE_INVALID "Size must be between 64 MiB and 64 GiB."
      mkdir -p "${path%/*}" 2>/dev/null
      build_swapfile "$path" "$size"
      printf '\036CHJ_STEP=create|ok|%s MiB\n' "$size"
      activate "$path" "$prio"; printf '\036CHJ_STEP=activate|ok|\n'
      [ "$persist" = 1 ] && fstab_apply "$path" persist "$prio" ;;
    activate)
      [ -e "$path" ] || fail SWAP_NOT_FOUND "The swap space does not exist."
      is_active "$path" && fail SWAP_ALREADY_ACTIVE "The swap space is already active."
      prio=$(resolve_prio "$path" "$prio")
      activate "$path" "$prio"; printf '\036CHJ_STEP=activate|ok|\n'
      if [ "$persist" = 1 ]; then fstab_apply "$path" persist keep; elif [ "$persist" = 0 ]; then fstab_apply "$path" remove keep; fi ;;
    deactivate)
      is_active "$path" || fail SWAP_NOT_ACTIVE "The swap space is not active."
      assert_swapoff_safe "$path"
      out=$(swapoff "$path" 2>&1) || fail SWAPOFF_FAILED "$out"; printf '\036CHJ_STEP=deactivate|ok|\n'
      [ "$persist" = 0 ] && fstab_apply "$path" remove keep ;;
    priority)
      [ "$prio" != keep ] || fail ARGUMENTS_INVALID "Choose automatic or an explicit priority."
      n=$(fstab_entry "$path"); current=$(runtime_prio "$path")
      [ -n "$n" ] || [ -n "$current" ] || [ -e "$path" ] || fail SWAP_NOT_FOUND "The swap space is neither active nor configured in /etc/fstab."
      # Already effective: explicit value equal, or automatic requested and the kernel assigned one (negative).
      same=0; case $prio:$current in -1:-*) same=1 ;; *) [ "$prio" = "$current" ] && same=1 ;; esac
      runtime=0; [ -n "$current" ] && [ "$apply" = now ] && [ $same = 0 ] && runtime=1
      # Check memory first, so that nothing is changed when the area cannot be swapped off safely.
      [ $runtime = 1 ] && assert_swapoff_safe "$path"
      if [ -n "$n" ]; then fstab_apply "$path" priority "$prio"; printf '\036CHJ_STEP=priority-saved|ok|%s\n' "$prio"
      elif [ "$persist" = 1 ]; then fstab_apply "$path" persist "$prio"; printf '\036CHJ_STEP=priority-saved|ok|%s\n' "$prio"
      else printf '\036CHJ_STEP=priority-saved|none|not in /etc/fstab\n'; fi
      if [ -z "$current" ]; then printf '\036CHJ_STEP=priority-runtime|skipped|inactive\n'
      elif [ $same = 1 ]; then printf '\036CHJ_STEP=priority-runtime|ok|already %s\n' "$current"
      elif [ $runtime = 1 ]; then reprioritize "$path" "$prio"; printf '\036CHJ_STEP=priority-runtime|ok|%s\n' "$(runtime_prio "$path")"
      else printf '\036CHJ_STEP=priority-runtime|pending|next activation or restart\n'; fi ;;
    persist)
      [ -e "$path" ] || is_active "$path" || fail SWAP_NOT_FOUND "The swap space does not exist."
      if [ "$persist" = 1 ]; then
        if [ -n "$(fstab_entry "$path")" ]; then printf '\036CHJ_STEP=fstab|ok|already present\n'; else fstab_apply "$path" persist "$(resolve_prio "$path" "$prio")"; fi
      else fstab_apply "$path" remove keep; fi ;;
    resize)
      managed_path "$path" || fail SWAP_MANUAL_ONLY "Only swap files at /swapfile*, /swap/* or /var/lib/swap/* are resized by CH-J."
      [ -f "$path" ] && [ ! -L "$path" ] || fail SWAP_NOT_FOUND "The swap file does not exist."
      [ "$size" -ge 64 ] && [ "$size" -le 65536 ] || fail SWAP_SIZE_INVALID "Size must be between 64 MiB and 64 GiB."
      prio=$(resolve_prio "$path" "$prio"); old=$(runtime_prio "$path")
      was_active=0
      if is_active "$path"; then assert_swapoff_safe "$path"; was_active=1; fi
      # The new file is built next to the old one first; the old file is replaced only after mkswap succeeded.
      if [ $was_active = 1 ]; then out=$(swapoff "$path" 2>&1) || fail SWAPOFF_FAILED "$out"; fi
      ( build_swapfile "$path" "$size" ) || { [ $was_active = 1 ] && try_swapon "$path" "$old"; fail SWAP_RESIZE_FAILED "The new swap file could not be created; the previous file was reactivated."; }
      printf '\036CHJ_STEP=resize|ok|%s MiB\n' "$size"
      if [ $was_active = 1 ]; then activate "$path" "$prio"; printf '\036CHJ_STEP=activate|ok|\n'; fi ;;
    delete)
      managed_path "$path" || fail SWAP_MANUAL_ONLY "Only swap files at /swapfile*, /swap/* or /var/lib/swap/* are deleted by CH-J; partitions are never deleted."
      [ -f "$path" ] && [ ! -L "$path" ] || fail SWAP_NOT_FOUND "The swap file does not exist."
      if is_active "$path"; then assert_swapoff_safe "$path"; out=$(swapoff "$path" 2>&1) || fail SWAPOFF_FAILED "$out"; printf '\036CHJ_STEP=deactivate|ok|\n'; fi
      fstab_apply "$path" remove keep
      rm -f -- "$path" || fail SWAP_DELETE_FAILED "The file could not be removed."
      printf '\036CHJ_STEP=delete|ok|\n' ;;
    *) fail ACTION_INVALID "Unsupported swap action." ;;
  esac
  status
  printf '\036CHJ_RESULT=ok\n'
}

case $op in
  safety-check) [ -n "${CHJ_SWAP_TEST_PROC:-}" ] || fail ACTION_INVALID "Test-only operation."; assert_swapoff_safe "$1"; printf 'safe\n' ;;
  fstab-test) [ -n "${CHJ_SWAP_TEST_PROC:-}" ] && [ -n "${CHJ_SWAP_TEST_FSTAB:-}" ] || fail ACTION_INVALID "Test-only operation."
    case $1 in resolve) resolve_prio "$2" "$3" ;; *) fstab_apply "$2" "$1" "$3" ;; esac ;;
  inspect) op_inspect ;;
  manage) op_manage "$@" ;;
  *) fail ACTION_INVALID "Unsupported operation." ;;
esac
