#!/bin/bash
INSTALLED=$(type -p update-rc.d)
pre_install() {
	# title			:uno pre installation
	# author		:Glenn Cady <theemahn@ultimateedition.info>
	# date			:03/08/2018
	# ============================================================================
	#Pull info we will use to compare against later
	IUSER=${SUDO_USER:-$USER}
	IHOME="/home/$IUSER"
	# Check inode of rootfs if anything other then 2 we are in a chroot environment
	# use above IUSER results to further our cause.& guarantee our success ;)
	# Inform user of current findings:
	root_inode=$(stat -c %i /);
	if [ -f /etc/xdg/autostart/uno.desktop ] ; then
		rm /etc/xdg/autostart/uno.desktop
	fi
	HOOKS="$(grep -Po '^\s*HOOKS=\(\K.*?(?=\))' /etc/mkinitcpio.conf | sed -E 's/\s+/ /g; s/\s+$//g')"
	RAMBOOTER=$(echo "${HOOKS}" | grep "ram-booter")
	if ! [[ "${RAMBOOTER}" ]]; then
		hooks="$(sed -E \
			's/^(.*(encrypt|udev|base)) (.*)/\1 ram-booter \3/g' \
			<<<"$hooks")"
		sed -Ei "s/^(\s*HOOKS=).*/\1\(${HOOKS}\)/g" /etc/mkinitcpio.conf
	fi
	#exit 0;
}
post_install() {
	/usr/bin/ram-booter -E --suppress
	if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
		if [ -x "/etc/init.d/uno" ]; then
			if [[ "${INSTALLED}" ]]; then
				update-rc.d uno defaults >/dev/null
				invoke-rc.d uno start || exit 1
			fi
		fi
		if [ -x "/etc/init.d/ram-booter" ]; then
			if [[ "${INSTALLED}" ]]; then
				update-rc.d ram-booter stop >/dev/null
			fi
		fi
	fi
}

post_upgrade() {
post_install
}
pre_remove() {
	/usr/bin/ram-booter -D --suppress
	if [ -x "/etc/init.d/uno" ]; then
		if [[ "${INSTALLED}" ]]; then
			invoke-rc.d uno stop || exit 1
		fi
	fi
}
post_remove() {
	if [ "${1}" = "purge" ] ; then
		if [[ "${INSTALLED}" ]]; then
			update-rc.d uno remove >/dev/null
		fi
	fi
	if [ "${1}" = "purge" ] ; then
		if [[ "${INSTALLED}" ]]; then
			update-rc.d ram-booter remove >/dev/null
		fi
	# Remove log file if it exists.  They are un-installing it.
		if [ -f "/var/log/ram-booter.log" ]; then
			rm -f /var/log/ram-booter.log
		fi
	fi
	# In case this system is running systemd, we make systemd reload the unit files
	# to pick up changes.
	if [ -d /run/systemd/system ] ; then
		systemctl --system daemon-reload >/dev/null || true
	fi
	exit 0
}
