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

# PROVIDE: ix-etc
# REQUIRE: middlewared earlykld ix-syncdisks
# BEFORE: disks

. /etc/rc.subr

copy_templates()
{
	# Copy over FreeNAS specific /etc template files
	for file in $(find /etc | grep '.template$' 2>/dev/null)
	do
		nfile=$(echo $file | sed 's|.template||g')
		cp ${file} ${nfile}
		if [ $? -ne 0 ] ; then
			echo "WARNING: Failed to copy template file $file -> $nfile"
		fi

		# Special handling for login.conf file that needs cap_mkdb run
		if [ "$nfile" = "/etc/login.conf" ] ; then
			cap_mkdb /etc/login.conf
		fi

		# We copy profile file to /usr/local/etc to reflect with upstream changes
		# https://forums.freebsd.org/threads/what-happened-to-etc-profile.78406/
		if [ "$nfile" = "/etc/profile" -a -f "$nfile" ]; then
			cp "$nfile" "/usr/local$nfile"
		fi
	done
}

generate_etc()
{
	copy_templates

	LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/midclt call --job true --job-print description certificate.dhparam_setup > /dev/null
	LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/midclt call etc.generate_checkpoint initial > /dev/null

	# etc rc plugin will generate rc.conf.freenas which needs to be re-read by /etc/rc script
	killall -ALRM sh
}

name="ix_etc"
start_cmd='generate_etc'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
