#!/bin/sh
set -e

PKGNAME="$1"
MODE="$2" # PRE-INSTALL, POST-INSTALL, DEINSTALL, POST-DEINSTALL

case "$MODE" in
POST-INSTALL)
	# install fsck tool and wrapper.
	err=0
	for i in e2fsck fsck_ext2fs ; do
		ln -f ${PKG_PREFIX}/sbin/${i} /sbin 2>/dev/null \
		|| cp -p ${PKG_PREFIX}/sbin/${i} /sbin \
		|| err=1
	done
	if test $err = 1 ; then
		echo '========================================================================'
		echo 'Warning: cannot install fsck to /sbin!'
		echo 'Requesting ext2fs to be checked from /etc/fstab can cause boot failures!'
		echo '========================================================================'
		echo ''
	fi
	#
	# install configuration file and update
	#
	if test -f ${PKG_PREFIX}/etc/mke2fs.conf; then
		if cmp -s ${PKG_PREFIX}/etc/mke2fs.conf.dist \
						${PKG_PREFIX}/etc/mke2fs.conf; then
			true
		else
			if grep -q ext4dev ${PKG_PREFIX}/etc/mke2fs.conf ; then
				cp -f -p ${PKG_PREFIX}/etc/mke2fs.conf.dist \
					${PKG_PREFIX}/etc/mke2fs.conf.e2fsprogs-new
				echo "==========================================================================="
				echo "Warning: installing mke2fs.conf in ${PKG_PREFIX}/etc/mke2fs.conf.e2fsprogs-new"
				echo "Check to see if you need to update your ${PKG_PREFIX}/etc/mke2fs.conf"
				echo "==========================================================================="
			else
				mv ${PKG_PREFIX}/etc/mke2fs.conf \
					 ${PKG_PREFIX}/etc/mke2fs.conf.e2fsprogs-old
				cp -f -p ${PKG_PREFIX}/etc/mke2fs.conf.dist \
					${PKG_PREFIX}/etc/mke2fs.conf
				echo "==========================================================================="
				echo "Your mke2fs.conf is too old.  Backing up old version in"
				echo "${PKG_PREFIX}/etc/mke2fs.conf.e2fsprogs-old.  Please check to see"
				echo "if you have any local customizations that you wish to preserve."
				echo "==========================================================================="
			fi
			echo " "
		fi
	else
		cp -f -p ${PKG_PREFIX}/etc/mke2fs.conf.dist \
			${PKG_PREFIX}/etc/mke2fs.conf
	fi
	;;
DEINSTALL)
	rm -f /sbin/fsck_ext2fs /sbin/e2fsck \
	|| echo "Could not remove /sbin/fsck_ext2fs /sbin/e2fsck. Please remove manually."
	if cmp -s ${PKG_PREFIX}/etc/mke2fs.conf \
		${PKG_PREFIX}/etc/mke2fs.conf.dist
	then
		rm -f ${PKG_PREFIX}/etc/mke2fs.conf
	else
		echo "If and only if you are deleting e2fsprogs forever,"
		echo "remember to delete ${PKG_PREFIX}/etc/mke2fs.conf."
	fi
	if test -f ${PKG_PREFIX}/etc/e2fsck.conf
	then
		echo "If and only if you are deleting e2fsprogs forever,"
		echo "remember to delete ${PKG_PREFIX}/etc/e2fsck.conf."
	fi
	;;
PRE-INSTALL|POST-DEINSTALL)
	true
	;;
esac
