#!/bin/sh

# Copyright (c) 2014-2018 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.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

USE_MFS_TMP=$(/usr/bin/grep -c 'use_mfs_tmp[^_]' /conf/config.xml)

# see if / is writable (aka. non-LiveCD boot)
if _tmpdir=$(mktemp -d -q /.diskless.XXXXXX); then
	# only remove the directory
	rmdir ${_tmpdir}
else
	# disable to avoid double /tmp mount in installer media
	USE_MFS_TMP=0
fi

mkdir -p /tmp

if [ ${USE_MFS_TMP} -ne 0 ]; then
	MAX_MFS_TMP=$(grep 'max_mfs_tmp' /conf/config.xml | sed 's/[^>]*>\([^<]*\)<.*/\1/')
	MAX_MEM_SYS=$(sysctl -n hw.physmem)

	if [ -z "${MAX_MFS_TMP}" ]; then
		# cap to 50% by default to avoid swapping
		MAX_MFS_TMP=50
	fi

	mount -t tmpfs -o mode=01777,size=$((MAX_MEM_SYS / 100 * MAX_MFS_TMP)) tmpfs /tmp
else
	rm -rf /tmp/*
	chmod 1777 /tmp
fi
