#!/usr/bin/env bash

# @pwn2owned

# Stop asking to save the key
rm -rf ~/.ssh/known_hosts

# Change to euphoria_scripts dir (parent of pushFiles, where iproxy/sshpass live)
cd "$(dirname "$0")/.."
echo "Working dir: $(pwd)"

# Kill any existing iproxy
killall iproxy 2>/dev/null
sleep 1

# Start iproxy
./iproxy 2222 44 > /dev/null 2>&1 &
IPROXY_PID=$!
sleep 3

# Test SSH connection
result=$(./sshpass -p 'alpine' ssh \
    -o StrictHostKeyChecking=no \
    -o UserKnownHostsFile=/dev/null \
    -o ConnectTimeout=5 \
    -o LogLevel=ERROR \
    -p 2222 root@localhost 'echo ok' 2>&1)

if ! echo "$result" | grep -q "ok"; then
    echo "SSH failed: $result"
    echo "Is the device jailbroken?"
    kill $IPROXY_PID 2>/dev/null
    exit 1
fi

echo "SSH connected!"

# Mount read-write
./sshpass -p 'alpine' ssh \
    -o StrictHostKeyChecking=no \
    -o UserKnownHostsFile=/dev/null \
    -o LogLevel=ERROR \
    -p 2222 root@localhost \
    'mount -o rw,union,update / 2>/dev/null; true'
sleep 1

# Pull mobileactivationd via openssl base64 (no sftp-server on jailbroken device)
echo "Pulling mobileactivationd..."
mkdir -p ./pulledFiles

./sshpass -p 'alpine' ssh \
    -o StrictHostKeyChecking=no \
    -o UserKnownHostsFile=/dev/null \
    -o LogLevel=ERROR \
    -p 2222 root@localhost \
    'openssl base64 -in /usr/libexec/mobileactivationd 2>/dev/null' \
    2>/dev/null | openssl base64 -d -out ./pulledFiles/PULLED_mobileactivationd

if [ -s ./pulledFiles/PULLED_mobileactivationd ]; then
    SIZE=$(ls -lah ./pulledFiles/PULLED_mobileactivationd | awk '{print $5}')
    echo "Pull success! Size: $SIZE"
    cp ./pulledFiles/PULLED_mobileactivationd ./pulledFiles/PULLED_mobileactivationd.original
    echo "Backup: ./pulledFiles/PULLED_mobileactivationd.original"
else
    echo "WARNING: Pull failed or file is empty!"
    kill $IPROXY_PID 2>/dev/null
    exit 1
fi

# Kill iproxy
kill $IPROXY_PID 2>/dev/null
wait $IPROXY_PID 2>/dev/null

echo ""
echo "Done! Open ./pulledFiles/PULLED_mobileactivationd in a hex editor."
echo ""
