#!/system/bin/sh

export NO_MAGISK=0
export NO_CONFIG=0
export MODPATH=@MODPATH@

if [[ -d /dev/tmp/magisk_img/$(basename ${MODPATH}) ]]; then
	OVERLAY_PATH=/dev/tmp/magisk_img/$(basename ${MODPATH})
elif [[ -d /dev/tmp/magisk_merge_img/$(basename ${MODPATH}) ]]; then
	OVERLAY_PATH=/dev/tmp/magisk_merge_img/$(basename ${MODPATH})
else
	OVERLAY_PATH=${MODPATH}
	[[ "${MODPATH}" != "/sbin/.core/"* ]] && NO_MAGISK=1
fi

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

[[ $(whoami) != "root" ]] && error "not running as root"

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
}

show_app_name () {
	aapt dump badging "${1}" 2>/dev/null | \
		grep "application: label" | \
		sed -e "s/.*label='//g;s/' icon.*//g"
}

add_override () {
	echo "  creating overlay: $(basename ${1})"
	mkdir -p "${OVERLAY_PATH}/system/${1}"
	touch "${OVERLAY_PATH}/system/${1}/.replace"
}

rm_override () {
	xapp=$(basename ${1})
	echo "  removing overlay: ${xapp}"
	rm -rf  "${OVERLAY_PATH}/system/${1}"
	sed -e "/^${xapp}$/d" -i "${config}"
}

update_overrides () {
	clear_overrides
	gen_overrides
}

gen_overrides () {
	OVERLAY_APPS=$(cat "${config}")

	echo "  creating Overlays in ${OVERLAY_PATH}"

	for app in ${OVERLAY_APPS}; do
		if [ -d /system/app/${app} ]; then
			add_override "app/${app}" ${OVERLAY_PATH}
		elif [ -d /system/priv-app/${app} ]; then
			add_override "priv-app/${app}" ${OVERLAY_PATH}
		else	echo "  app \"${app}\" is not installed"
		fi
	done
}

list_overrides () {
	LIST_APPS=($(find "${OVERLAY_PATH}/system/app" -name "*.replace"))
	for app in "${LIST_APPS[@]}"; do
		APPS=(${APPS[@]} "$(basename $(dirname "${app}"))")
	done

	LIST_PRIV_APPS=($(find "${OVERLAY_PATH}/system/priv-app" -name "*.replace"))
	for app in "${LIST_PRIV_APPS[@]}"; do
		PRIV_APPS=(${PRIV_APPS[@]} "$(basename $(dirname "${app}"))")
	done

	echo "Overlays exist for following applications in /system/app:

$(printf '  * %s\n' "${APPS[@]}")

Overlays exist for following applications in /system/priv-app:

$(printf '  * %s\n' "${PRIV_APPS[@]}")
"
}

show_nooverrides () {
	echo " >> processing /system/app"

	for app in /system/app/*/*.apk; do
		sysname=$(basename "${app}" .apk)
		if [[ ! -f ${OVERLAY_PATH}/system/app/${sysname}/.replace ]]; then
			humname=$(show_app_name "${app}")
			S_APPS="${S_APPS}
	* ${sysname}		|(${humname})"
		fi
	done

	echo " >> processing /system/priv-app"

	for app in /system/priv-app/*/*.apk; do
		sysname=$(basename "${app}" .apk)
		if [[ ! -f ${OVERLAY_PATH}/system/priv-app/${sysname}/.replace ]]; then
			humname=$(show_app_name "${app}")
			S_PRIV_APPS="${S_PRIV_APPS}
	* ${sysname}		|(${humname})"
		fi
	done

	echo "Non-Overlayed applications in /system/app:

$(printf '* %s\n' "${S_APPS[@]}" | column -t -s \|)

Non-Overlayed applications in /system/priv-app:

$(printf '* %s\n' "${S_PRIV_APPS[@]}" | column -t -s \|)
"
}

clear_overrides () {
	echo "  removing Overlays from ${OVERLAY_PATH}"
	RM_APPS=($(find "${OVERLAY_PATH}/system/app" -name "*.replace"))
	for app in "${RM_APPS[@]}"; do
		echo "  removing override: $(basename $(dirname ${app}))"
		rm -rf "$(dirname "${app}")"
	done

	RM_PRIV_APPS=($(find "${OVERLAY_PATH}/system/priv-app" -name "*.replace"))
	for app in "${RM_PRIV_APPS[@]}"; do
		echo "  removing override: $(basename $(dirname ${app}))"
		rm -rf "$(dirname "${app}")"
	done
}

genconfig () {
	[[ ! -f "${config}" ]] && config="/data/.nanodroid-overlay"

	APPS=($(find "${OVERLAY_PATH}/system/app" -name "*.replace"))
	PRIV_APPS=($(find "${OVERLAY_PATH}/system/priv-app" -name "*.replace"))

	if [[ ${APPS[*]} != "" ]]; then
		for app in "${APPS[@]}"; do
			xapp=$(basename $(dirname ${app}))
			echo "  adding ${xapp} to configuration"
			echo "${xapp}" >> "${config}"
		done
	fi

	if [[ ${PRIV_APPS[*]} != "" ]]; then
		for app in "${PRIV_APPS[@]}"; do
			xapp=$(basename $(dirname ${app}))
			echo "  adding ${xapp} to configuration"
			echo "${xapp}" >> "${config}"
		done
	fi
}

# check for configuration files
config_locations="/sdcard /external_sd @ZIPDIR@ /data /dev/tmp/install"
get_config .nanodroid-overlay

if [[ ${NO_MAGISK} -eq 0 ]]; then

if [[ -f ${config} ]]; then
	export config
else
	genconfig
	export config="/data/.nanodroid-overlay"
fi

case ${1} in
	-l | --list )
		list_overrides
	;;

	-a | --add )
		if [ ! -z ${2} ]; then
			if [[ -d /system/app/${2} ]]; then
				add_override "app/${2}"
				echo "${2}" >> "${config}"
			elif [[ -d /system/priv-app/${2} ]]; then
				add_override "priv-app/${2}"
				echo "${2}" >> "${config}"
			else	echo "app \"${2}\" is not installed"
			fi
		fi
	;;

	-r | --remove )
		if [ ! -z ${2} ]; then
			if [[ -f ${OVERLAY_PATH}/system/app/${2}/.replace ]]; then
				rm_override "app/${2}"
			elif [[ -f ${OVERLAY_PATH}/system/priv-app/${2}/.replace ]]; then
				rm_override "priv-app/${2}"
			else	echo "No override for \"${2}\" found"
			fi
		fi
	;;

	-u | --update )
		update_overrides
	;;

	-s | --show )
		show_nooverrides
	;;

	-c | --clear )
		clear_overrides
	;;

	-g | --genconfig )
		rm -f ${config}
		genconfig
	;;

	-x | --create )
		gen_overrides
	;;

	* )
		echo "nanodroid-overlay

Manages Overlay (Pseudo Debloat feature)

Options:
-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
"
	;;
esac

else
	error "*** Overlay feature is not available in System Mode! ***"
fi
