#!/bin/bash
# /etc/rc.d/swap — activate the persistent swap file at boot.
#
# The area lives at /State/swapfile on the disk root, so it survives reboots;
# a live boot has no writable disk and this script simply finds no file and
# says so rather than failing the rest of startup.
#
# SIZE IS CAPPED AT 4095 MiB DELIBERATELY. swapon(2) refuses an area of 4 GiB
# or more on this kernel -- measured 2026-09-08 on the Dell, bisected exactly:
# 512/2048/3072/4095 MiB all activate, 4096 MiB and 8191 MiB are both refused
# with "swap header claims more pages than the area holds". The boundary is
# exactly 2^32 bytes, so a 32-bit byte quantity wraps somewhere below
# parse_swap_header(); SWAP_MAX_SLOTS is 2097152 (8 GiB) and the ext4 mapper's
# own arithmetic is 64-bit, so it is neither of those. Until that is found,
# asking for 8 GiB gets NO swap at all rather than less swap, which is why this
# script does not simply request the larger size and hope.
SWAPFILE=${SWAPFILE:-/State/swapfile}

case "$1" in
    start)
        if [ ! -f "$SWAPFILE" ]; then
            echo "rc: swap: $SWAPFILE not present — no swap" >&2
            exit 0
        fi
        # Already active (a re-run of rc) is success, not an error: this kernel
        # tracks exactly one area and a second swapon returns EBUSY.
        if grep -q "^${SWAPFILE} " /proc/swaps 2>/dev/null; then
            exit 0
        fi
        chmod 600 "$SWAPFILE" 2>/dev/null || true
        if ! swapon "$SWAPFILE" 2>/dev/null; then
            echo "rc: swap: swapon $SWAPFILE FAILED — continuing without swap" >&2
            exit 0
        fi
        # ASSERT IT IS ACTUALLY ON. swapon's exit status is not enough: the
        # failure this guards against reported nothing on stdout and left
        # SwapTotal at 0, so the only trustworthy check is the kernel's table.
        if ! grep -q "^${SWAPFILE} " /proc/swaps 2>/dev/null; then
            echo "rc: swap: swapon returned success but /proc/swaps is empty" >&2
        fi
        ;;
    stop)
        swapoff "$SWAPFILE" 2>/dev/null || true
        ;;
    *)
        echo "usage: $0 start|stop" >&2; exit 1 ;;
esac
exit 0
