#!/bin/sh -


export LANG=en_US.UTF-8

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

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

_get_orig_snapshot(){
	if which apfs_snapshot 1>>/dev/null 2>>/dev/null; then
		_orig_snapshot="$(apfs_snapshot -l / | sed -n '1p')"
		return
	fi
	if which snaputil 1>>/dev/null 2>>/dev/null; then
		_orig_snapshot="$(snaputil -l / | sed -n '1p')"
		return
	fi
	if which snappy 1>>/dev/null 2>>/dev/null; then
		_orig_snapshot="$(snappy -lf / | sed -n '2p')"
		return
	fi
	#Damn it, why is there nothing? Use 'orig-fs' to try
	_orig_snapshot='orig-fs'
}

_umount(){
	i='1'
	while [ 1 -le 2 ]; do
		if umount -f '/var/MobileSoftwareUpdate/mnt1'; then
			if mount | grep -q 'on /var/MobileSoftwareUpdate/mnt1 ('; then
				echo '[=] umount snapshot failure'
			else
				break
			fi
		fi
		if [ "${i}" = '100' ]; then
			break
		fi
		i="$((i+1))"
	done
	unset i
	if mount | grep -q 'on /var/MobileSoftwareUpdate/mnt1 ('; then
		echo '[=] umount snapshot failure'
	else
		echo '[=] umount snapshot success'
	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 {} \;
	echo '[=] clean caches success'
}

_restore(){
	_orig_snapshot="$(ioreg -p IODeviceTree -l | grep boot-manifest-hash)"
	if [ -n "${_orig_snapshot}" ]; then
		_orig_snapshot="${_orig_snapshot#*<}"
		_orig_snapshot="$(echo ${_orig_snapshot%>*} | tr 'a-z' 'A-Z')"
		_orig_snapshot="com.apple.os.update-${_orig_snapshot}"
	fi
	if mount | grep -q "${_orig_snapshot}@/dev/disk0s1s1 on "; then
		i='1'
		while [ 1 -le 2 ]; do
			if umount -f "${_orig_snapshot}@/dev/disk0s1s1"; then
				if ! mount | grep -q "${_orig_snapshot}@/dev/disk0s1s1"; then
					break
				fi
			fi
			if [ "${i}" = '100' ]; then
				break
			fi
			i=$((i+1))
		done
		unset i
	fi
	unset _orig_snapshot
	rm -rf "/var/MobileSoftwareUpdate/mnt1" && mkdir -p "/var/MobileSoftwareUpdate/mnt1"
	_get_orig_snapshot
	mount_apfs -s "${_orig_snapshot}" "/" "/var/MobileSoftwareUpdate/mnt1" 1>>/dev/null 2>>/dev/null
	echo '[=] mount snapshot success'
	if [ -e "/var/MobileSoftwareUpdate/mnt1/System/Library/Fonts/" ]; then
			echo '[*] Recovering'
		if rsync -a --delete "/var/MobileSoftwareUpdate/mnt1/System/Library/Fonts" "/System/Library/" >>/dev/null; then
			echo '[=] Recovery complete'
		else
			echo '[x] Recovery failure'
		fi
		_umount
	else
		echo '[x] Error: Font file not found'
		_umount
		exit 1
	fi
	_clean_caches
}


case "${1}" in
	-h | --help)
		_usage
		exit 0
	;;
	-r)
		_restore
		echo 'Respring!'
		echo 'Respring!'
		echo 'Respring!'
	;;
	-R)
		_restore
		killall -9 backboardd
	;;
	-c)
		_clean_caches
	;;
	-C)
		_clean_caches
		killall -9 backboardd
	;;
	*)
		_usage
		exit 1
	;;
esac
