#!/bin/sh -


if [ -f '/etc/profile' ]; then
	. /etc/profile
	_tmp='/tmp'
	_daemon='/Library/LaunchDaemons/com.nan.reality-tmp.plist'
elif [ -f '/var/jb/etc/profile' ]; then
	. /var/jb/etc/profile
	_tmp='/var/jb/tmp'
	_daemon='/var/jb/Library/LaunchDaemons/com.nan.reality-tmp.plist'
else
	echo 'Where the fuck "profile"?' 1>&2
	exit 1
fi
if readlink "${_tmp}" | grep -q '^var/tmp'; then
	_tmp="$(echo "${_tmp}" | sed 's#tmp#var/tmp#')"
fi
if [ -e '/rootfs' ]; then
	_root='/rootfs'
fi
export LANG=en_US.UTF-8

_randnum(){
	if [ -z "${2}" ]; then
		tr -dc 'A-Za-z0-9' < /dev/urandom | head -c "${1}"
	else
		tr -dc "${1}" < /dev/urandom | head -c "${2}"
	fi
}

_new_tmp="${_root}/tmp/$(_randnum 'A-Z0-9' '8')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '12')"
while [ '1' -le '2' ]; do
	if mkdir "${_new_tmp}"; then
		break
	else
		_new_tmp="${_root}/tmp/$(_randnum 'A-Z0-9' '8')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '12')"
	fi
done
echo "new reality tmp: ${_new_tmp}"
chmod -R 1777 "${_new_tmp}"
if test -e "${_tmp}"; then
	mv "${_tmp}" "${_new_tmp}/$(_randnum 'A-Z0-9' '8')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '4')-$(_randnum 'A-Z0-9' '12')"
else
	rm -rf "${_tmp}"
fi
ln -sf "${_new_tmp}" "${_tmp}"
launchctl unload "${_daemon}" 1>>/dev/null 2>>/dev/null
exit 0
