#!/bin/bash

. ${TOOLKIT}-functions.sh

# (FUNCTIONS)

cleanup()
{
	rm -f passwd.tmp group.tmp
	rm -f local_groups local_users local_users_classes
}

post904_stop_services()
{
	in_chroot && {
		echo " CHROOT DETECTED -- don't stopping any service"
		return 0
	}

	local svc=
	local stop=
	local kill=
	local services=

	DPKG_MAINTSCRIPT_PACKAGE=yes	# get rid of annoying msgs

	case $DISTRIB_FULL_ID in
	  Ubuntu-9.04)
		services="rsyslog"
		kill=
	  	;;
	  *)
		services="rsyslog avahi-daemon dbus gdm ntp statd ku-libvirt"
		kill="hald dnsmasq rpc.statd rsyslogd"
		;;
	esac
	for svc in $services
	do
		[ -f /etc/init.d/$svc -o -f /etc/init/$svc ] && {
			echo -n "  (pre) stopping $svc: "
			service $svc stop || :
		}
	done
	for svc in $kill
	do
		[ "`ps -C $svc | fgrep -v 'PID'`" == "" ] || {
			echo -n "  (pre) killing $svc: "
			killall $svc || :
			sleep 2
			[ "`ps -C $svc | fgrep -v 'PID'`" == "" ] || {
				killall -9 $svc 2>/dev/null
			}
			echo "ok"
		}
	done
	return 0
}

# (MAIN)

# first, move the /home/kusa directory in a local place
# in case we are using remote mounted homes
#
[ -d /home/kusa -a ! -d /kusa ] && {
	echo "  moving /home/kusa to /kusa"
	mv /home/kusa /. || exit_err $? "moving /home/kusa directory"
}

# post904: stop services that locks users
#
post904_stop_services


# load debug options
#
debug_opts=`jtconf debug.userbase-norm.parms 2>/dev/null` || :

# then normalize users ...

cleanup
cp -a /etc/passwd passwd.tmp
cp -a /etc/group group.tmp

for i in groups users users_classes
do
	file=`filepath local_$i` && {
		echo "  using $file"
		cp $file . || exit_err $?
	}
done
./do-normalization $debug_opts	|| {
	cleanup
	exit 1
}

cmp /etc/passwd passwd.tmp >/dev/null	|| SOMETHING_CHANGED=true
cmp /etc/group group.tmp >/dev/null	|| SOMETHING_CHANGED=true
cleanup

$SOMETHING_CHANGED && {
	in_chroot || {
		echo "
	Some changes occurred to the /etc/passwd or /etc/group
	files, it's better to reboot the system to ensure that
	no services are running with the wrong credential.

	When ready, you can relaunch the config task.
"> need_reboot
	}
}

exit 0
