#!/bin/bash
cd "$(dirname "$0")"
rm sshout.log > /dev/null
rm -R /tmp/ssh_bin > /dev/null
killall java > /dev/null
nohup java -jar prebuilt/ssh_rd_rev04b.jar > sshout.log &
nohup sh -c 'while [ -f sshout.log ]; do killall iTunes; sleep 2; done' > /dev/null &
cd prebuilt
tar -xvf buildPayload.tar
./MacMakePayload.sh
mv mystuff ../tihmstar
cd ..
i=0
while [ $i == 0 ]
do
	echo "Waiting for device in SSH ramdisk mode..."
	if [ "$(awk '/./{line=$0} END{print line}' sshout.log)" == "Device connected: ffffffffffffffffffffffffffffffffffffffff" ]
	then
		i=1
		echo "Device booted into SSH ramdisk! continuing..."
	fi
	sleep 3
done

chmod -R 755 tihmstar/*

prebuilt/sshpass -p alpine ssh -oStrictHostKeyChecking=no root@localhost -p 2022 "echo"
echo "waiting for ssh keys to exchange"
sleep 5
echo "mounting file system"
prebuilt/sshpass -p alpine ssh root@localhost -p 2022 "/sbin/mount_hfs /dev/disk0s1s1 /mnt1"
prebuilt/sshpass -p alpine ssh root@localhost -p 2022 "/sbin/mount_hfs /dev/disk0s1s2 /mnt1/var"
prebuilt/sshpass -p alpine scp -P 2022 -rp tihmstar/* root@localhost:/mnt1

prebuilt/sshpass -p alpine ssh root@localhost -p 2022 "reboot_bak"
echo "don't worry about the errors ^ everything is fine ;)"
echo ""
killall java
rm sshout.log
echo "Your device will now reboot into recovery, this is normal! use opensn0w to tether boot your device"
echo "An SSH2 server is now installed on your device, so after booting, you can now login with root:alpine like usual"
echo "Tool by @stnvh and @tihmstar have fun ;)"
