#!/bin/sh -


if [ -f '/etc/profile' ]; then
	. /etc/profile
	if which jbroot 2>>/dev/null 1>>/dev/null; then
		_root_path='/rootfs'
		_jb_root_path="$(jbroot | sed 's#\/$##')"
		_daemons='/Library/LaunchDaemons'
	else
		echo "wait...isn't this not roothide?"
		exit 1
	fi
elif [ -f '/var/jb/etc/profile' ]; then
	. /var/jb/etc/profile
	_root_path=''
	_jb_root_path="$(readlink -f '/var/jb')"
	_daemons='/var/jb/Library/LaunchDaemons'
else
	echo 'Where the fuck "profile"?' 1>&2
	exit 1
fi
_p_file="${_jb_root_path}/var/mobile/Library/Preferences/com.nan.auto-bindfs.plist"

_exit(){
	echo launchctl unload "${_daemons}/com.nan.auto-bindfs.plist"
	exit 0
}

if [ -f "${_jb_root_path}/basebin/.safe_mode" ]; then
	_exit
fi
if [ -f '/var/mobile/.not_auto_mount' ]; then
	_exit
fi
if ! plutil -key 'Enable' "${_jb_root_path}/var/mobile/Library/Preferences/com.nan.auto-bindfs.plist" | grep -q '^1$'; then
	_exit
fi
if [ ! -f "${_p_file}" ]; then
	_exit
fi

i='0'
while [ '1' -le '2' ]; do
	_path="$(plutil -key 'path' -key "${i}" "${_p_file}" 2>&1)"
	if echo "${_path}" | grep -q '^Error: Object not found at keypath'; then
		break
	else
		if mount_bindfs "${_path}"; then
			_reboot_userspace='1'
		fi
	fi
	i="$((i+1))"
done
if [ -n "${_reboot_userspace}" ]; then
	sleep 1
	launchctl reboot userspace
fi
_exit
