#!/var/jb/bin/sh -


if ! id -u | grep -q '^0$'; then
	sudo "${0}" "$@"
	exit 0
fi

_command="${0##*/}"

_usage(){
	echo "Usage: ${_command} [OPTIONS...]
	-h	Print this help
	-c	Clean caches
	-r	Restore Fonts"
}

_check_mnt1(){
	if [ -e "/var/MobileSoftwareUpdate/mnt1" ]; then
		_del_mnt1='0'
	else
		mkdir "/var/MobileSoftwareUpdate/mnt1"
		_del_mnt1='1'
	fi
}

_mount_orig(){
	case "$(mount | grep '/dev/disk0s1s1')" in
		*@/dev/disk0s1s1*)
			mount_apfs -o ro '/dev/disk0s1s1' '/var/MobileSoftwareUpdate/mnt1'
			_path='/var/jb/'
			;;
		*)
			mount_apfs -s 'orig-fs' '/' '/var/MobileSoftwareUpdate/mnt1'
			_path='/'
			;;
	esac
}

_umount(){
	umount -f '/var/MobileSoftwareUpdate/mnt1'
	if [ "${_del_mnt1}" = '1' ]; then
		rm -rf '/var/MobileSoftwareUpdate/mnt1'
	fi
}

_restore_font(){
	if [ -e "/var/MobileSoftwareUpdate/mnt1/System/Library/Fonts/" ]; then
		echo '[*] Recovering'
		if rsync -a --delete "/var/MobileSoftwareUpdate/mnt1/System/Library/Fonts" "${_path}System/Library/"; then
			echo '[*] Recovery complete'
		else
			echo '[*] Recovery exception'
		fi
	else
		_umount
		echo '[*] Error: Font file not found'
		exit 6
	fi
}

_clean_caches(){
	rm -rf '/var/mobile/Library/Caches/com.apple.keyboards/'
	rm -rf '/var/mobile/Library/Caches/com.apple.UIStatusBar/'
	rm -rf "/var/mobile/Library/Caches/TelephonyUI"*
	find "/var/mobile/Containers/Data/Application" -maxdepth 4 -type d -iname "TelephonyUI*" -exec rm -rf {} \;
}


case "${1}" in
	-h | --help)
		_usage
		exit 0
	;;
	-r)
		_check_mnt1
		_mount_orig 2>>/dev/null
		_restore_font
		_umount
		_clean_caches
		if [ "${_path}" = '/var/jb/' ]; then
			echo 'Reboot userspace!'
			echo 'Reboot userspace!'
			echo 'Reboot userspace!'
		else
			echo 'Respring!'
			echo 'Respring!'
			echo 'Respring!'
		fi
	;;
	-R)
		_check_mnt1
		_mount_orig 2>>/dev/null
		_restore_font
		_umount
		_clean_caches
		if [ "${_path}" = '/var/jb/' ]; then
			launchctl reboot userspace
		else
			killall -9 backboardd
		fi
	;;
	-c)
		_clean_caches
		echo '[*] clean caches success'
	;;
	-C)
		_clean_caches
		killall -9 backboardd
		echo '[*] clean caches success'
	;;
	*)
		_usage
		exit 2
	;;
esac
