#!/bin/bash

. ${TOOLKIT}-functions.sh

# remove old/incomplete stuff
save_status=$SOMETHING_CHANGED
purgefiles /sbin/vhspare-*
SOMETHING_CHANGED=$save_status

case $DISTRIB_RELEASE in
	10.04)
		installfile vmbuilder-10.04.cfg $HOME/.vmbuilder.cfg root:root 644  || exit $?
		;;
esac

# SASL: docs says that libvirt search libvirt.conf in /etc/sasl2, but it's wrong,
#	the daemon uses the old directory name /etc/sasl, so we create a symlink
#	if not exists
#
updatelink /etc/sasl2 /etc/sasl

file="/etc/libvirt/passwd.db"
user="kvm"
newflag=
msg=

if [ -f $file ]
then
	sasldblistusers2 -f $file | grep -q "^$user@" || {
		msg="default user '$user' not found in $file"
		newflag="-c"
	}
else
	msg="file $file not exists, creating"
fi
[ "$msg" != "" ] && {
	putwarning "LIBVIRT SASL USER" \
		$msg "; a new user '$user' will be created with the same password," \
		"use 'saslpasswd2 -f $file $user' to change password"
	echo "$user" | saslpasswd2 $newflag -f $file $user
}


[ -f /etc/init/libvirt-bin ] && stop libvirt-bin || :

purgefiles /etc/init.d/libvirt* /etc/init/libvirt* /etc/rc*.d/libvirt* \
	/etc/default/libvirt-bin \
	/etc/logrotate.d/libvirtd.* /etc/logrotate.d/libvirtd

add_init_script 20 ku-libvirt || exit $?

ofile=/etc/default/libvirtd
file=/etc/default/ku-libvirt
[ -f $ofile ] && {
	echo "  renaming $ofile -> $file"
	mv $ofile $file
	SOMETHING_CHANGED=true
}

[ -f $file ] || {
	installfile ku-libvirt.default $file root:root 664
}


# KSM DAEMON?
#
file=/etc/default/qemu-kvm
out=qemu-kvm
ksm_enabled=0
getconfirm virt.ksm_enabled && ksm_enabled=1

sed -e "s/^KSM_ENABLED=.*/KSM_ENABLED=$ksm_enabled # changed by $TOOLKIT/" $file >$out
installfile $out $file root:root 664




$SOMETHING_CHANGED && {
	restart_service ku-libvirt libvirtd
	[ -f /etc/init/qemu-kvm.conf ] && restart qemu-kvm
}

exit 0
