#!/bin/sh

# Copyright (c) 2014-2016 Franco Fichtner <franco@opnsense.org>
# Copyright (c) 2004-2010 Scott Ullrich <sullrich@gmail.com>
# Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>
# All rights reserved.

stty status '^T' 2> /dev/null

# Set shell to ignore SIGINT (2), but not children;
# shell catches SIGQUIT (3) and returns to single user.
#
trap : 2
trap "echo 'Boot interrupted'; exit 1" 3

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

echo "Mounting filesystems..."

# tunefs may refuse otherwise
mount -fr /

while read FS_PART FS_MNT FS_TYPE FS_MORE; do
	# only tune our own file systems
	if [ "${FS_TYPE}" != "ufs" ]; then
		continue;
	fi

	if echo "${FS_MORE}" | grep -iq nosoft; then
		# appending "# nosoft" to the /etc/fstab entry
		# will allow to strip trim and leave it disabled
		tunefs -n disable ${FS_MNT}
	else
		# enables soft updates
		tunefs -n enable ${FS_MNT}
	fi

	FS_DEV=$(echo ${FS_PART} | awk 'match($0, /^\/dev\/(gpt|ufs)\/.+$/) { print substr( $0, RSTART + 5, RLENGTH - 5 )}')
	if [ -n "${FS_DEV}" ]; then
		FS_DEV=$(glabel status -as | grep ${FS_DEV} | awk 'match($3, /^[a-z]+[0-9]+/) { print substr( $3, RSTART, RLENGTH )}')
	fi
	if [ -z "${FS_DEV}" ]; then
		FS_DEV=$(echo ${FS_PART} | awk 'match($0, /^\/dev\/[a-z]+[0-9]+/) { print substr( $0, RSTART + 5, RLENGTH - 5 )}')
	fi
	if [ -n "${FS_DEV}" ]; then
		FS_TRIM=$(camcontrol identify ${FS_DEV} | grep TRIM | awk '{ print $5; }')
		if [ "${FS_TRIM}" = "yes" ]; then
			if echo "${FS_MORE}" | grep -iq notrim; then
				# appending "# notrim" to the /etc/fstab entry
				# will allow to strip trim and leave it disabled
				tunefs -t disable ${FS_MNT}
			else
				# enables TRIM
				tunefs -t enable ${FS_MNT}
			fi
		fi
	fi
done < /etc/fstab

attempts=0
while [ ${attempts} -lt 3 ]; do
	fsck -C -y /
	fsck -C -y /
	if mount -a 2>/dev/null; then
		# bail if all is well
		break
	fi
	attempts=$((attempts+1))
done

# see if / is writable (aka. non-LiveCD boot)
if _tmpdir=$(mktemp -d -q /.diskless.XXXXXX); then
	# only remove the directory
	rmdir ${_tmpdir}
else
	# fake a writeable environment in some subdirs
	for i in conf etc home root usr var; do
		mkdir -p /tmp/.cdrom/${i}
		mount_unionfs /tmp/.cdrom/${i} /${i}
	done
fi

# regenerate groups and users for base
/usr/local/etc/rc.recover base > /dev/null

# set keyboard map if needed
/etc/rc.d/syscons onestart

# set up config directory structure
mkdir -p /conf/backup
mkdir -p /conf/sshd

# Bootstrap config.xml if necessary
if [ ! -f /conf/config.xml ]; then
	echo -n "Bootstrapping config.xml..."
	cp /usr/local/etc/config.xml /conf/config.xml
	echo "done."
fi

# Bootstrap openssl.cnf for port if necessary
if [ ! -f /usr/local/openssl/openssl.cnf ]; then
	echo -n "Bootstrapping openssl.cnf..."
	cp /etc/ssl/openssl.cnf /usr/local/openssl/openssl.cnf
	echo "done."
fi

# Enable console output if its muted.
/sbin/conscontrol mute off >/dev/null

setup_mfs_link()
{
	ROOT=${1}
	MFS=${2}
	NAME=${3}

	# Create dummy directory to for MFS-bound
	# directories that require a persistent
	# storage underneath to run.

	if [ ! -d "${ROOT}${MFS}/${NAME}" ]; then
		mkdir -p "${ROOT}${MFS}" "${MFS}/${NAME}"
		mv "${MFS}/${NAME}" "${ROOT}${MFS}"
		# create a symlink underneath as well
		ln -s "${ROOT}${MFS}/${NAME}" "${MFS}/${NAME}"
	fi
}

install_mfs_link()
{
	ROOT=${1}
	MFS=${2}
	NAME=${3}

	# Redirect persistent, but MFS-bound
	# directory after tmpfs mount.

	mkdir -p "${MFS}"
	ln -s "${ROOT}${MFS}/${NAME}" "${MFS}/${NAME}"
}

remove_mfs_link()
{
	ROOT=${1}
	MFS=${2}
	NAME=${3}

	# Persistent copies of MFS-bound directories
	# still there must be moved back into place.

	if [ -d "${ROOT}${MFS}/${NAME}" ]; then
		mkdir -p "${MFS}"
		# reverse the recovery symlink before
		# moving back the original database
		rm -f "${MFS}/${NAME}"
		mv "${ROOT}${MFS}/${NAME}" "${MFS}/"
	fi
}

# USE_MFS_TMP also catches and overrides USE_MFS_VAR (pre-16.7 compat)
# At some point we want to flip use_mfs_tmpvar to use_mfs_var instead.
USE_MFS_VAR=`/usr/bin/grep -c use_mfs_tmpvar /conf/config.xml`
USE_MFS_TMP=`/usr/bin/grep -c use_mfs_tmp /conf/config.xml`

if [ ${USE_MFS_TMP} -ne 0 ]; then
	mount -t tmpfs -o mode=01777 tmpfs /tmp
fi

if [ ${USE_MFS_VAR} -ne 0 ]; then
	echo -n "Setting up memory disks..."

	setup_mfs_link /root /var/cache opnsense-update
	setup_mfs_link /root /var/log bsdinstaller
	setup_mfs_link /root /var/cache pkg
	setup_mfs_link /root /var/db pkg
	setup_mfs_link /root /var crash

	mount -t tmpfs tmpfs /var

	install_mfs_link /root /var/cache opnsense-update
	install_mfs_link /root /var/log bsdinstaller
	install_mfs_link /root /var/cache pkg
	install_mfs_link /root /var/db pkg
	install_mfs_link /root /var crash

	echo "done."
else
	remove_mfs_link /root /var/cache opnsense-update
	remove_mfs_link /root /var/log bsdinstaller
	remove_mfs_link /root /var/cache pkg
	remove_mfs_link /root /var/db pkg
	remove_mfs_link /root /var crash
fi

# make some directories in /var
mkdir -p /var/run /var/log /var/etc /var/db/entropy /var/at/jobs \
    /var/empty /var/tmp /var/crash /var/cron/tabs

# work around the fact that shutdown(8) doesn't clean up this file
rm -f /var/run/nologin

# set up and recover a crash dump before activating swap
/usr/local/etc/rc.crashdump
swapon -a

# write /var/run/dmesg.boot
/etc/rc.d/dmesg onestart

rm -rf /tmp/*
chmod 1777 /tmp

echo -n "."
/sbin/ldconfig -elf /usr/lib /usr/local/lib /lib
/etc/rc.d/ldconfig start 2>/dev/null

# Launching kbdmux(4)
if [ -f "/dev/kbdmux0" ]; then
	echo -n "."
	/usr/sbin/kbdcontrol -k /dev/kbdmux0 < /dev/console
	[ -c "/dev/atkbd0" ] && kbdcontrol -a atkbd0 < /dev/console
	[ -c "/dev/ukbd0" ] && kbdcontrol -a ukbd0 < /dev/console
fi

echo "done."

# Regenerate groups and users for packages
/usr/local/etc/rc.recover pkg > /dev/null

# Recreate capabilities DB
/usr/bin/cap_mkdb /etc/login.conf

# Set up the correct php.ini content
/usr/local/etc/rc.php_ini_setup

# Perform major updates
for STAGE in B P; do
	if opnsense-update -${STAGE}; then
		# ideally reroot with `-r', but panics on ZFS
		reboot
	fi
done

# Startup configd
/usr/local/etc/rc.d/configd start

# Restore backups from previous shutdown (if any)
/usr/local/etc/rc.backup_dhcpleases restore
/usr/local/etc/rc.backup_netflow restore
/usr/local/etc/rc.backup_rrd restore

# Execute the early syshook / plugin commands
/usr/local/etc/rc.syshook early

# Let the PHP-based configuration subsystem set up the system now
echo -n "Launching the init system..."
touch /var/run/booting
/usr/local/etc/rc.bootup || exit 1
rm /var/run/booting

# Execute the normal syshook / plugin commands
/usr/local/etc/rc.syshook start

echo -n "Starting CRON... "
cd /tmp && /usr/sbin/cron -s 2>/dev/null
echo "done."

# starting standard rc scripts
/usr/local/etc/rc.opnsense start

/usr/local/sbin/beep.sh start

/usr/local/etc/rc.initial.banner

exit 0