#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-loader
# REQUIRE: ix-update

. /etc/rc.freenas

: ${AUTOTUNE_REBOOT=true}

# Update an file that persists across reboots with a new file if something's
# changed, or nuke it if the file was unchanged.
#
# TODO: move to rc.freenas.
#
# Parameters:
#   1 - Old file
#   2 - New file
#
# Returns...
#   0 - updated something.
#   1 - no change.
#   2 - an error occurred.
update_persistent_file()
{
	local new old rc

	old=$1
	new=$2

	rc=1
	if [ ! -f "$new" ]; then
		:
	elif cmp -s "$old" "$new"; then
		rm -f "$new"
	else
		rc=2
		if mv "$new" "$old"; then
			rc=0
		fi
	fi
	return $rc
}

loader_serial()
{
	local serial_enable=0

	serial_enable=$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "SELECT adv_serialconsole FROM system_advanced ORDER BY -id LIMIT 1")

	if [ "${serial_enable}" != "0" ]; then
		serial_port=$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "SELECT adv_serialport FROM system_advanced ORDER BY -id LIMIT 1")
		echo "comconsole_port=\"${serial_port}\""
		serial_speed=$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "SELECT adv_serialspeed FROM system_advanced ORDER BY -id LIMIT 1")
		echo "comconsole_speed=\"${serial_speed}\""
		echo 'boot_multicons="YES"'
		echo 'console="comconsole,vidconsole"'
	fi
}

loader_xen()
{
	local xen_guest=0
	local tmp

	tmp=$(/usr/local/sbin/dmidecode -s system-product-name)
	if [ $? -eq 0 ]; then
	    if [ "$tmp" = "HVM domU" ]; then
		echo 'hint.hpet.0.clock="0"'
	    fi
	fi
}

loader_user() {

	local IFS="|"
	local f="tun_var tun_value tun_comment"
	eval local $f
	local sf=$(var_to_sf $f)
	${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} \
	"SELECT $sf FROM system_tunable WHERE tun_enabled = 1 AND tun_type = 'loader' ORDER BY id" | \
	while eval read -r $f; do
		(echo -n "${tun_var}=\"${tun_value}\""
		 if [ -n "${tun_comment}" ]; then
			echo -e " # ${tun_comment}"
		 else
			echo
		 fi)
	done

}

loader_debugkernel()
{
	local debugkernel_enable=0

	debugkernel_enable=$(${FREENAS_SQLITE_CMD} ${FREENAS_CONFIG} "
	SELECT
		adv_debugkernel

	FROM
		system_advanced
	
	ORDER BY
		-id
	LIMIT 1")

	if [ "${debugkernel_enable}" != "0" ]; then
		echo 'kernel="kernel-debug"'
		echo 'module_path="/boot/kernel-debug;/boot/modules;/usr/local/modules"'
	else
		echo 'kernel="kernel"'
		echo 'module_path="/boot/kernel;/boot/modules;/usr/local/modules"'
	fi
}

loader_ha()
{
	local node

	node=$(ha_node)

	if [ "${node}" = "A" ]; then
		echo "kern.cam.ctl.ha_id=1"
	elif [ "${node}" = "B" ]; then
		echo "kern.cam.ctl.ha_id=2"
	else
		echo "kern.cam.ctl.ha_id=0"
	fi
}

do_autotune()
{
	local autotune

	export PATH=$PATH:/usr/local/bin:/usr/local/sbin

	autotune=/usr/local/bin/autotune
	ec=0
	if [ -x $autotune ]
	then

		$autotune \
				--kernel-reserved=1073741824 \
				--userland-reserved=2417483648

		ec=$?
		# Values changed based on recommendations. Reboot [eventually].
		if [ $ec -eq 2 ]
		then
			ec=0
			reboot_now=true
		fi
	fi
	return $ec
}

generate_boot_loader_conf_local()
{
	local settings
	local tmp
	local first_install=0

	settings="serial user debugkernel ha xen"

	tmp=$(mktemp /tmp/tmp.XXXXXX)

	for setting in $settings; do
		eval "loader_${setting}" >> $tmp
	done

	# Using the ix-loader script to also do post-first-install stuff
        # We should create a seperate ix-firstinstall script
        # if we add more things later.
        if [ -f $FIRST_INSTALL_SENTINEL ]; then
	    first_install=1
            # Delete sentinel file before making clone as we
            # we do not want the clone to have the file in it.
            rm -rf $FIRST_INSTALL_SENTINEL

	    # Creating pristine boot environment from the "default"
            echo "Creating 'Initial-Install' boot environment..."
            /usr/local/sbin/beadm create -e default Initial-Install
        fi

	update_persistent_file /boot/loader.conf.local $tmp

	if [ $? = 0 -o $first_install = 1 ]; then
	    /usr/local/sbin/grub-mkconfig -o /boot/grub/grub.cfg > /dev/null
	fi
}

generate_loader_confs()
{
	reboot_now=false

	do_autotune
	generate_boot_loader_conf_local

	if $AUTOTUNE_REBOOT && $reboot_now; then
		shutdown -r now
	fi
}

generate_loader_confs_noreboot()
{
	do_autotune
	generate_boot_loader_conf_local
}

name="ix-loader"
start_cmd='generate_loader_confs'
reload_cmd='generate_loader_confs_noreboot'
stop_cmd=':'
extra_commands='reload'

load_rc_config $name
run_rc_command "$1"
