#!/bin/bash

. ${TOOLKIT}-functions.sh

msgfile="$RUNDIR/msg.tmp"

KUWATCHER_REMOVEFILES=

# /etc/fstab modified?
#
$SOMETHING_CHANGED && {

    cat $msgfile

    in_chroot || {

	# swap
	#
	swap=`jtconf apu.swap_device 2>/dev/null` && {
		# disable if already running
		for dev in `swapon -s | sed -e '1d' -e 's/ .*//'`
		do
			[ $dev = $swap ] && {
				swapoff $dev || exit $?
				break
			}
		done

		# (re)create and (re)activate if device present
		# if not maybe that we are running on chrooted filesystem
		[ -e $swap ] && {
			label=`jtconf apu.swap_label`
			echo "    creating swap on $swap (LABEL=$label) ... "
			mkswap -L $label $swap >$RUNDIR/tmp.err 2>&1 || {
				status=$?
				cat $RUNDIR/tmp.err
				exit $status
			}
			echo "    activating swap ... "
			swapon $swap || exit $?
		}
	}


	# must mount datadir?
	#
	datalabel=`jtconf apu.data_label 2>/dev/null` && {
		[ -e /dev/disk/by-label/CFDATA ] && {
			datadir=`jtconf path.datadir`	|| exit_missing_define path.datadir
			mountpoint $datadir || {
				mount LABEL=CFDATA || exit $?
			}
		}
	}

    } # in_chroot

} # $SOMETHING_CHANGED



# grub configuration
#
[ -d /boot/grub ] || {
	mkdir /boot/grub || exit $?
}

echo "(hd0) /dev/hda"	>/boot/grub/device.map

# grub options (only server for apu, at the moment)
#
export temp_grub_opts=`jtconf grub.options_srv 2>/dev/null`
echo "  using server grub options: $temp_grub_opts"

# serial console
#
speed=$(jtconf apu.serial_speed)

installfile grub2.default	/etc/default/grub	root:root 644 || exit $?

grep -q "^T0:.*$speed" /etc/inittab || {
	echo "  adding/replacing getty on ttyS0 in /etc/inittab"
	egrep -v '#\[ku|^T0:' /etc/inittab >inittab.tmp

	echo -e "\n#[ku]" >>inittab.tmp
	echo "T0:23:respawn:/sbin/getty -L ttyS0 $speed" >>inittab.tmp

	installfile inittab.tmp /etc/inittab root:root 644
}


# not ubuntu standard, kernel does not set clock at boot, we need
# to enable it manually via normal /etc/init.d script
# we can't use add_init_script function because works on rc0.d
# instead of rc6.d on systems stop and doesn't follows 100-S rule
#
##if [ -f /etc/init.d/hwclock.sh ]
	##update-rc.d hwclock.sh defaults
##else
	### clean mess make by kusa on systems > 9.04
	##purgefiles /etc/init.d/[KS]??hwclock.sh
##fi



file="auto-apu-check-wan"
target="/etc/kuwatcher/conf.d/$file"

wan_ip=$(jtconf apu-leds.wan_ip 2>/dev/null) || :

if [ "X$wan_ip" != "X" ]
then
	installfile $file $target		root:root 400 || exit $?
else
	KUWATCHER_REMOVEFILES="$KUWATCHER_REMOVEFILES $target"
fi

# cleanup
#
purgefiles $KUWATCHER_REMOVEFILES


$SOMETHING_CHANGED && {
	restart_service kuwatcher
	update-grub
}

exit 0
