#!/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..."

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}

	# cleanup configuration files from previous instance
	# (does not work with install media unfortunately)
	/bin/rm -rf /var/run/*
	/bin/rm -rf /var/etc/*
	/bin/rm -rf /var/tmp/*
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

# !!! migration code for OPNsense <= 15.1.7, do not remove !!!
if [ -d "/cf/conf" ]; then
	/bin/rm -f /conf
	/bin/mv /cf/conf /conf
	/bin/rm -rf /cf
fi
# !!! migration code for OPNsense <= 15.1.7, do not remove !!!

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

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

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

# probe for a persistent core dump device
/usr/local/etc/rc.dumpon

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

# Bootstrap config.xml if necessary
if [ ! -f /conf/config.xml ]; then
	echo -n "Bootstrapping config.xml..."
	/bin/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..."
	/bin/cp /etc/ssl/openssl.cnf /usr/local/openssl/openssl.cnf
	echo "done."
fi

# Disable APM on ATA drives. Leaving this on will kill drives long-term, especially laptop drives, by generating excessive Load Cycles.
if [ -f /usr/local/etc/rc.disable_hdd_apm ]; then
	/usr/local/etc/rc.disable_hdd_apm
fi

#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

# sync pw database after mount.
rm -f /etc/spwd.db.tmp
/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd

# 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} -eq 0 ]; then
	mdmfs -S -M -s 4m md /var/run
else
	USE_MFS_TMP_SIZE=`/usr/bin/grep use_mfs_tmp_size /conf/config.xml | /usr/bin/cut -f2 -d'>' | /usr/bin/cut -f1 -d'<'`
	if [ ! -z ${USE_MFS_TMP_SIZE} ] && [ ${USE_MFS_TMP_SIZE} -gt 0 ]; then
		tmpsize="${USE_MFS_TMP_SIZE}m"
	else
		tmpsize="40m"
	fi

	USE_MFS_VAR_SIZE=`/usr/bin/grep use_mfs_var_size /conf/config.xml | /usr/bin/cut -f2 -d'>' | /usr/bin/cut -f1 -d'<'`
	if [ ! -z ${USE_MFS_VAR_SIZE} ] && [ ${USE_MFS_VAR_SIZE} -gt 0 ]; then
		varsize="${USE_MFS_VAR_SIZE}m"
	else
		varsize="60m"
	fi

	echo -n "Setting up memory disks..."

	if [ ! -d /root/var/db/pkg ]; then
		/bin/mkdir -p /root/var/db
		/bin/mv /var/db/pkg /root/var/db/
	fi

	mdmfs -S -M -s ${tmpsize} md /tmp
	mdmfs -S -M -s ${varsize} md /var

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

	echo "done."
fi

/sbin/swapon -a
/usr/local/etc/rc.savecore

if [ -d /root/var/db/pkg ]; then
	# User must have just disabled RAM disks,
	# let's move these back into place.
	/bin/mkdir -p /var/db
	/bin/mv /root/var/db/pkg /var/db/
fi

# make some directories in /var
/bin/mkdir -p /var/run /var/log /var/etc /var/db/entropy /var/at/jobs/ /var/empty 2>/dev/null

echo -n "Creating symlinks..."

# Repair symlinks if they are broken
if [ -f /etc/newsyslog.conf ]; then
	/bin/rm -f /etc/newsyslog.conf
fi
if [ ! -L /etc/syslog.conf ]; then
	/bin/rm -rf /etc/syslog.conf
	if [ ! -f /var/etc/syslog.conf ]; then
		touch /var/etc/syslog.conf
	fi
	/bin/ln -s /var/etc/syslog.conf /etc/syslog.conf
fi

# Remove symlinks that are no longer needed
if [ -L /etc/resolv.conf ]; then rm /etc/resolv.conf; fi
if [ -L /etc/hosts ]; then /bin/rm /etc/hosts; fi

# Setup compatibility link for packages that
# have trouble overriding the PREFIX configure
# argument since we build our packages in a
# separated PREFIX area
# Only create if symlink does not exist.
if [ ! -h /tmp/tmp ]; then
    /bin/ln -hfs / /tmp/tmp
fi

/bin/rm -rf /tmp/*
/bin/chmod 1777 /tmp

if [ ! -L /etc/dhclient.conf ]; then
    /bin/rm -rf /etc/dhclient.conf
fi

if [ ! -d /var/tmp ]; then
	/bin/mkdir -p /var/tmp
fi

set -T
trap "echo 'Reboot interrupted'; exit 1" 3

# Remove old nameserver resolution files
/bin/rm -f /var/etc/nameserver*

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

DEFAULT_LOG_FILE_SIZE=`/usr/local/bin/xmllint --xpath 'string(//pfsense/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
		/usr/bin/touch /var/log/$logfile.log
	else
		if [ ! -f /var/log/$logfile.log ]; then
			if [ "$ENABLEFIFOLOG" -gt "0" ]; then
				# generate fifolog files
				/usr/sbin/fifolog_create -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log
			else
				/usr/local/sbin/clog -i -s ${DEFAULT_LOG_FILE_SIZE} /var/log/$logfile.log
			fi
		fi
	fi
done

# change permissions on newly created fifolog files.
/bin/chmod 0600 /var/log/*.log

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..."
/bin/rm -f /conf/backup/backup.cache
/bin/rm -f /root/lighttpd*
/usr/bin/touch /var/run/booting
/usr/local/etc/rc.bootup

# end of boot process, remove status file
/bin/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
/usr/local/bin/minicron 240 /var/run/ping_hosts.pid /usr/local/bin/ping_hosts.sh

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

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

/bin/chmod a+rw /tmp/.

# 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.
	/usr/bin/touch /var/run/gmirror_active
	# Setup monitoring/notifications
	/usr/local/bin/minicron 60 /var/run/gmirror_status_check.pid /usr/local/sbin/gmirror_status_check.php
fi

/usr/local/bin/beep.sh start 2>&1 >/dev/null

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

exit 0