#!/bin/sh

# Copyright (c) 2014-2015 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

	# enables soft updates
	tunefs -n enable ${FS_MNT}

	# enables TRIM
	FS_DEV=$(echo ${FS_PART} | awk 'match($0, /\/dev\/([a-z]+[0-9]+)/) { print substr( $0, RSTART, RLENGTH )}')
	FS_TRIM=$(camcontrol identify ${FS_DEV} | grep TRIM | awk '{ print $5; }')
	if [ "${FS_TRIM}" = "yes" ]; then
		tunefs -t enable ${FS_MNT}
	fi
done < /etc/fstab

attempts=0
while [ ${attempts} -lt 3 ]; do
	if mount -a 2>/dev/null; then
		# bail if all is well
		break
	fi
	fsck -y /
	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

# mount repo if available
if [ -d /root/core ]; then
	make -C /root/core mount
fi

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

# rewrite message of the day
/etc/rc.d/motd onestart

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

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

# 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

# Disable APM on ATA drives.  Leaving this on will kill
# drives long-term, especially laptop drives, by generating
# excessive load cycles.
ATAIDLE=/usr/local/sbin/ataidle
for i in /dev/ad?; do
	if [ ! -e ${i} ]; then
		continue;
	fi
	SUPPORTED=`${ATAIDLE} ${i} | grep "APM Supported" | awk '{print $3;}'`
	if [ "${SUPPORTED}" = "yes" ] ; then
		echo Disabling APM on $i
		${ATAIDLE} -P 0 ${i}
	fi
done

#Eject CD devices on 3G modems
MANUFACTURER="huawei|zte"
CDDEVICE=`dmesg |egrep -ie "($MANUFACTURER)" | awk -F: '/cd/ {print $1}'`
if [ "$CDDEVICE" != "" ]; then
	cdcontrol -f /dev/"$CDDEVICE" eject
fi

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

USE_MFS_TMPVAR=`/usr/bin/grep -c use_mfs_tmpvar /conf/config.xml`
if [ ${USE_MFS_TMPVAR} -ne 0 ]; then
	echo -n "Setting up memory disks..."

	if [ ! -d /root/var/db/pkg ]; then
		mkdir -p /root/var/db
		mv /var/db/pkg /root/var/db
		# create a symlink underneath as well
		# to fix early boot pkg(8) issues:
		ln -s /root/var/db/pkg /var/db/pkg
	fi

	mount -t tmpfs -o mode=01777 tmpfs /tmp
	mount -t tmpfs tmpfs /var

	mkdir -p /var/db
	ln -s /root/var/db/pkg /var/db/pkg

	echo "done."
elif [ -d /root/var/db/pkg ]; then
	# User must have just disabled RAM disks,
	# let's move these back into place.
	mkdir -p /var/db
	# reverse the recovery symlink before moving
	# back the original database:
	rm -f /var/db/pkg
	mv /root/var/db/pkg /var/db/
fi

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

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

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

rm -rf /tmp/*
chmod 1777 /tmp

echo -n "."
DISABLESYSLOGCLOG=`/usr/bin/grep -c disablesyslogclog /conf/config.xml`
LOG_FILES="system filter dhcpd vpn pptps poes l2tps openvpn portalauth ipsec ppps relayd wireless lighttpd ntpd gateways resolver routing"

DEFAULT_LOG_FILE_SIZE=`/usr/local/bin/xmllint --xpath 'string(//opnsense/syslog/logfilesize)' /conf/config.xml`
if [ ! ${DEFAULT_LOG_FILE_SIZE} ]; then
	DEFAULT_LOG_FILE_SIZE=511488
fi

for logfile in $LOG_FILES; do
	if [ "$DISABLESYSLOGCLOG" -gt "0" ]; then
		touch /var/log/$logfile.log
	else
		if [ ! -f /var/log/$logfile.log ]; then
			clog -i -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log
		fi
	fi
	chmod 0600 /var/log/$logfile.log
done

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."

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

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

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

# let the PHP-based configuration subsystem set up the system now
echo -n "Launching the init system..."
rm -f /root/lighttpd*
touch /var/run/booting
/usr/local/etc/rc.bootup
rm /var/run/booting

# If a shell was selected from recovery
# console then just drop to the shell now.
if [ -f "/tmp/donotbootup" ]; then
	echo "Dropping to recovery shell."
	exit 0
fi

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

# Start ping handler every 240 seconds
minicron 240 /var/run/ping_hosts.pid /usr/local/sbin/ping_hosts.sh

# Start account expire handler every hour
minicron 3600 /var/run/expire_accounts.pid /usr/local/etc/rc.expireaccounts

# Start alias url updater every 24 hours
minicron 86400 /var/run/update_alias_url_data.pid /usr/local/etc/rc.update_alias_url_data

# Check for GEOM mirrors
GMIRROR_STATUS=`/sbin/gmirror status`
if [ "${GMIRROR_STATUS}" != "" ]; then
	# Using a flag file at bootup saves an expensive exec/check on each page load.
	touch /var/run/gmirror_active
	# Setup monitoring/notifications
	minicron 60 /var/run/gmirror_status_check.pid /usr/local/sbin/gmirror_status_check.php
fi

/usr/local/sbin/beep.sh start

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

exit 0