#!/bin/sh
# DF-0053 phase 1 helper - create ONE jail with N IPs and a deep path.
# Run as root:  sh setup_jail.sh <n_ips>

set -u

N_IPS=${1:-16}

# Clean any previous attempts
pkill -9 -f '/s$' 2>/dev/null
sleep 1

rm -rf /tmp/jt
mkdir -p /tmp/jt

# Deep chroot path - one mkdir per level (mkdir -p mangles long paths on DF).
p=/tmp/jt
depth=0
while [ "$depth" -lt 60 ]; do
    p="$p/lllllllllllllll"
    if ! mkdir "$p" 2>/dev/null; then
        echo "setup_jail: mkdir failed at depth $depth"
        break
    fi
    depth=$((depth+1))
done
echo "setup_jail: depth=$depth path_len=$(echo -n "$p" | wc -c)"

# Verify the deep path is real (jail will fail with realpath() otherwise).
if [ ! -d "$p" ]; then
    echo "setup_jail: ERROR - deep path does not exist on disk: $p"
    exit 1
fi

# Static sleeper binary, copied into the chroot as /s.
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
cp /tmp/jt/s "$p/s"

# 60-char hostname - long enough that 'JID hostname fullpath' > 1024 bytes.
host=hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

# Comma-separated IP list of N_IPS 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: N_IPS=$N_IPS ips_len=$(echo -n "$ips" | wc -c)"

# Launch jail, fully detached so SSH returns.
/usr/sbin/jail "$p" "$host" "$ips" /s </dev/null >/tmp/jt/jout 2>&1 &
sleep 3

# Verify the jail actually started.
if [ -s /tmp/jt/jout ]; then
    echo "setup_jail: jail produced output (failure):"
    cat /tmp/jt/jout
fi
njails=$(/usr/sbin/jls 2>/dev/null | wc -l)
echo "setup_jail: jls line count (1 header + N jails) = $njails"
