# 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 test of the swapoff safety rule.
PROC=${CHJ_SWAP_TEST_PROC:-/proc}
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 ]; }
valid_prio() { case $1 in -1) return 0 ;; ''|*[!0-9]*) return 1 ;; esac; [ "$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"; }
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
}

fstab_entry() { awk -v p="$1" '$1==p && $3=="swap" { print NR; exit }' "$FSTAB" 2>/dev/null; }
# Rewrites /etc/fstab atomically: removes the swap entry for $1, optionally appends a new one. Other lines stay byte-identical.
fstab_set() {
  path=$1; persist=$2; prio=$3
  [ -f "$FSTAB" ] || fail FSTAB_MISSING "/etc/fstab does not exist."
  [ ! -L "$FSTAB" ] || fail FSTAB_UNSAFE "/etc/fstab is a symbolic link."
  stamp=$(date -u +%Y%m%dT%H%M%SZ)
  cp -p "$FSTAB" "$FSTAB.chj-backup-$stamp" || 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 p="$path" '!($1==p && $3=="swap") { print }' "$FSTAB" > "$tmp" || { rm -f "$tmp"; fail FSTAB_WRITE_FAILED "fstab could not be rewritten."; }
  if [ "$persist" = 1 ]; then
    options=sw; [ "$prio" != "-1" ] && options="sw,pri=$prio"
    printf '%s none swap %s 0 0 %s\n' "$path" "$options" "$MARK" >> "$tmp"
  fi
  chmod --reference="$FSTAB" "$tmp" 2>/dev/null || chmod 644 "$tmp"
  chown --reference="$FSTAB" "$tmp" 2>/dev/null || chown 0:0 "$tmp"
  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 have systemctl && [ -d /run/systemd/system ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi
  printf '\036CHJ_STEP=fstab|ok|backup %s\n' "$FSTAB.chj-backup-$stamp"
}

# 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
}

activate() {
  target=$1; prio=$2
  if [ "$prio" = "-1" ]; then out=$(swapon "$target" 2>&1); else out=$(swapon -p "$prio" "$target" 2>&1); fi
  [ $? -eq 0 ] || fail SWAPON_FAILED "swapon $target failed: $out"
}

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'
  [ -r "$FSTAB" ] && awk '$3=="swap" || /^[^#]*[[:space:]]swap[[:space:]]/ { print NR "|" $0 }' "$FSTAB"
  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 ] || fail ARGUMENTS_INVALID "Invalid arguments."
  action=$1; path=$2; size=$3; prio=$4; persist=$5
  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
  lock
  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)
      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_set "$path" 1 "$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."
      activate "$path" "$prio"; printf '\036CHJ_STEP=activate|ok|\n'
      [ "$persist" = keep ] || { [ -n "$(fstab_entry "$path")" ] && [ "$persist" = 1 ]; } || fstab_set "$path" "$persist" "$prio" ;;
    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 ] && [ -n "$(fstab_entry "$path")" ] && fstab_set "$path" 0 "$prio" ;;
    priority)
      if is_active "$path"; then
        assert_swapoff_safe "$path"
        out=$(swapoff "$path" 2>&1) || fail SWAPOFF_FAILED "$out"
        activate "$path" "$prio"
      fi
      printf '\036CHJ_STEP=priority|ok|%s\n' "$prio"
      [ -n "$(fstab_entry "$path")" ] && fstab_set "$path" 1 "$prio" ;;
    persist)
      [ -e "$path" ] || fail SWAP_NOT_FOUND "The swap space does not exist."
      fstab_set "$path" "$persist" "$prio" ;;
    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."
      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 ] && swapon "$path" >/dev/null 2>&1; 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
      [ -n "$(fstab_entry "$path")" ] && fstab_set "$path" 0 "$prio"
      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' ;;
  inspect) op_inspect ;;
  manage) op_manage "$@" ;;
  *) fail ACTION_INVALID "Unsupported operation." ;;
esac
