#!/bin/sh
# DF-0053 phase 1 - one-shot jail setup. Builds the deep path, /s sleeper,
# and launches the jail all in one process so no ssh disconnect can kill it.
#
# Run as root:  sh setup_jail_v3.sh <depth> <n_ips>

set -u

DEPTH=${1:-60}
N_IPS=${2:-4}

# 1. Kill any prior jails + sleepers
pkill -9 jail 2>/dev/null
pkill -9 -f "/s$" 2>/dev/null
sleep 2

# 2. Fresh start
rm -rf /tmp/jt
mkdir -p /tmp/jt

# 3. Static sleeper binary
cat > /tmp/jt/s.c <<'C'
#include <unistd.h>
int main(void){ for(;;) pause(); return 0; }
C
cc -static -O2 -o /tmp/jt/s /tmp/jt/s.c

# 4. Build deep path one level at a time, copying /s into the deepest dir.
p=/tmp/jt
n=0
while [ "$n" -lt "$DEPTH" ]; do
    p="$p/lllllllllllllll"
    if ! mkdir "$p" 2>/dev/null; then
        echo "setup_jail_v3: mkdir failed at depth=$n"
        break
    fi
    n=$((n+1))
done
PLEN=$(printf '%s' "$p" | wc -c)
echo "setup_jail_v3: depth=$n path_len=$PLEN"

# 5. Copy sleeper into chroot as /s
cp /tmp/jt/s "$p/s"
if [ ! -f "$p/s" ]; then
    echo "setup_jail_v3: ERROR - /s missing after cp; trying install"
    install /tmp/jt/s "$p/s"
fi
ls -la "$p/s" 2>&1 | head -1

# 6. Max-length hostname
host=$(printf 'h%.0s' $(seq 1 255))

# 7. N_IPS comma-separated IPv4 addresses
ips=10.0.0.1
i=2
while [ "$i" -le "$N_IPS" ]; do
    ips="$ips,10.0.0.$i"
    i=$((i+1))
done
echo "setup_jail_v3: n_ips=$N_IPS ips_len=${#ips}"

# 8. Launch jail in background.  Sleeper /s inside keeps prison alive
#    after this script and the ssh session exit.
/usr/sbin/jail "$p" "$host" "$ips" /s </dev/null >/tmp/jt/jout 2>&1 &
sleep 4

echo "--- jout (errors) ---"
cat /tmp/jt/jout 2>/dev/null
echo "--- jls ---"
/usr/sbin/jls
echo "--- sleeper ---"
pgrep -lf "/s$"
