#!/system/bin/sh

export MODID=@MODID@
export MODE=@MODE@

OVERLAY_PATH=""

[ -f /dev/tmp/install/CommonInstaller ] && MODE=${MODE}_INSTALL
[ -f /tmp/backuptool.functions ] && MODE=${MODE}_INSTALL
[ -f /postinstall/tmp/backuptool.functions ] && MODE=${MODE}_INSTALL

# detect whether we need to remount /system or / in system mode
if grep -q " $(readlink -f /system) " /proc/mounts 2>/dev/null; then
	remount_point=/system
else	remount_point=/
fi

error () {
	echo "!! ${@}"
	exit 1
}

if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
	if [ -d "/data/adb/modules_update/${MODID}" ]; then
		OVERLAY_PATH="/data/adb/modules_update/${MODID}"
	elif [ -d "/data/adb/modules/${MODID}" ]; then
		OVERLAY_PATH="/data/adb/modules/${MODID}"
	else
		error "couldn't find NanoDroid!"
	fi
fi

grep_prop() {
	[ -f /vendor/build.prop ] && \
		FILES="/system/build.prop /vendor/build.prop" || \
		FILES="/system/build.prop"

	sed -n "s/^${1}=//p" ${FILES} | head -n 1
}

show_help () {

	echo "nanodroid-overlay

Magisk Mode: Manages Overlays (Pseudo Debloat feature)
System Mode: Manages Moved-Outs (Force Debloat feature)

Options Magisk Mode:
-a | --add		[appname]	add override for app [appname]
-r | --remove		[appname]	remove override for app [appname]
-s | --show				show non-overriden /system applications
-l | --list				show all overriden /system applications
-x | --create				create all overrides
-u | --update				update all overrides (= clear + create)
-c | --clear				remove all overrides
-g | --genconfig			(re-)create configuration from existing overrides

Options System Mode:
-a | --add		[appname]	add override for app [appname]
-r | --remove		[appname]	remove override for app [appname] from configuration
-s | --show				show non-overriden /system applications
-x | --create				create all overrides
"

	exit 0
}

if [ "${MODE}" != "SYSTEM_INSTALL" -a "${MODE}" != "MAGISK_INSTALL" ]; then
	test "$(whoami)" != "root" && error "not running as root"
fi

get_config () {
	config=""
	config_exists=0
	for path in ${config_locations}; do
		if test -r "${path}/${1}" -a -f "${path}/${1}"; then
			config="${path}/${1}"
			config_exists=1
			return
		fi
	done
}

overrides_add_intern () {
	sysdir=${1}
	app=${2}

	if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
		echo "  creating overlay: ${app}"
		mkdir -p "${OVERLAY_PATH}/${sysdir}/${app}"
		touch "${OVERLAY_PATH}/${sysdir}/${app}/.replace"
	else
		echo "  removing app: ${app}"
		rm -rf "${sysdir}/${app}"
	fi

	grep -q "^${app}$" "${config}" 2>/dev/null || echo "${app}" >> "${config}"
}

overrides_add () {
	[ "${MODE}" = "SYSTEM" ] && mount -orw,remount ${remount_point}

	for app in ${@}; do
		for path in ${app_locations}; do
			[ -d ${path}/${app} ] && overrides_add_intern ${path} ${app}
		done
	done

	[ "${MODE}" = "SYSTEM" ] && mount -oro,remount ${remount_point}
}

overrides_remove_intern () {
	sysdir=${1}
	app=${2}

	if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
		echo "  removing overlay: ${app}"
		rm -rf "${OVERLAY_PATH}/${sysdir}/${app}"
	else
		echo "  overrides_remove() does nothing in System Mode!"
	fi

	sed -e "/^${app}$/d" -i "${config}"
}

overrides_remove () {
	for app in ${@}; do
		if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
			for path in ${app_locations}; do
				[ -f ${OVERLAY_PATH}/${path}/${app}/.replace ] && overrides_remove_intern ${path} ${app}
			done
		else
			# only remove entry from config file (if it exists)
			overrides_remove_intern app ${app}
		fi
	done

}

overrides_list () {
	if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
		for path in ${app_locations}; do
			if [ -d ${OVERLAY_PATH}/${path} ]; then
				app_int=""
				echo -e "\n ** Overrides for ${path}:"
				for app in $(find "${OVERLAY_PATH}/${path}" -name "*.replace"); do
					app_int="\n  * $(basename $(dirname "${app}"))${app_int}"
				done
				echo -e "${app_int}" | sort
			fi
		done
	else
		echo "  overrides_list() does nothing in System Mode!"
	fi
}

overrides_list_non () {
	if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
		for path in ${app_locations}; do
			if [ -d ${path} ]; then
				app_int=""
				echo -e "\n ** Non-Overriden apps for ${path}:"
				for app in $(find "${path}" -mindepth 1 -maxdepth 1 -type d); do
					[ ! -d ${OVERLAY_PATH}/${app} ] &&  app_int="\n  * $(basename ${app})${app_int}"
				done
				echo -e "${app_int}" | sort
			fi
		done
	else
		for path in ${app_locations}; do
			if [ -d ${path} ]; then
				echo -e "\n ** Non-Overriden apps for ${path}:"
				for app in $(find "${path}" -mindepth 1 -maxdepth 1 -type d); do
					app_int="\n  * $(basename ${app})${app_int}"
				done
				echo -e "${app_int}" | sort
			fi
		done
	fi

}

overrides_clear () {
	if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
		echo "  removing Overlays from ${OVERLAY_PATH}"
		for path in ${app_locations}; do
			for app in $(find "${OVERLAY_PATH}/${path}" -name "*.replace" 2>/dev/null); do
				echo "  removing override: $(basename $(dirname ${app}))"
				rm -rf "$(dirname "${app}")"
			done
		done
	else
		echo "  overrides_clear() does nothing in System Mode!"
	fi
}

overrides_genconfig () {
	if [ "${MODE}" = "MAGISK" -o "${MODE}" = "MAGISK_INSTALL" ]; then
		rm -f ${config}
		touch ${config}

		for path in ${app_locations}; do
			for app in $(find "${OVERLAY_PATH}/${path}" -name "*.replace" 2>/dev/null); do
				xapp=$(basename $(dirname ${app}))
				echo "  adding ${xapp} to configuration"
				grep -q "^${xapp}$" "${config}" 2>/dev/null || echo "${xapp}" >> "${config}"
			done
		done
	else
		echo "  overrides_genconfig() does nothing in System Mode!"
	fi
}

# check for configuration files
config_locations="/data/media/0 /external_sd /sdcard1 /data /system/addon.d /tmp"
media_rw=$(grep "^/dev/block.*/mnt/media_rw" /proc/mounts \
	| cut -d " " -f 2 \
	| cut -d "/" -f 4)
ext_storage="/storage/${media_rw}"

[ -r "${ext_storage}" ] && config_locations="${ext_storage} ${config_locations}"

get_config .nanodroid-overlay

app_locations="/system/app /system/priv-app /system/reserve /system/product/app /system/product/priv-app /system/system_ext/app /system/system_ext/priv-app"

[[ -f ${config} ]] && export config || config=/data/media/0/.nanodroid-overlay

opt=${1}
[[ -z ${opt} ]] && show_help || shift

case ${opt} in
	-l | --list )		overrides_list ;;
	-a | --add )		overrides_add "${@}" ;;
	-r | --remove )		overrides_remove "${@}" ;;
	-s | --show )		overrides_list_non ;;
	-c | --clear )		overrides_clear ;;
	-x | --create )
		if [ -f "${config}" ]; then
			overrides_add "$(grep -E -v '^(#|[[:space:]]*$)' "${config}")"
		fi
	;;
	-g | --genconfig )	overrides_genconfig ;;

	-u | --update )
		[ "${MODE}" = "MAGISK" ] && overrides_clear
		overrides_add "$(grep -E -v '^(#|[[:space:]]*$)' "${config}")"
	;;

	* ) show_help ;;
esac

