#! /bin/sh -
#
# Prepare to halt or reboot the system
#
# Copyright (c) 2017-2020 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

RC="[${0##*/}]"	# To reflect the name of the script between [].
umask 022
IFS='
 	'
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/usr/sbin:/bin:/usr/bin
LC_ALL=C

# Set linefeed mode to avoid staircase effect
stty onlcr 0>&1

# Be immune to the following signals
trap "" HUP INT QUIT ABRT TERM

# Save system clock

if grep -q '^RC_HWCLOCK=local' /etc/rc.conf
then
    echo "${RC}: Saving hardware clock in local time"
    hwclock --systohc --localtime
else
    echo "${RC}: Saving hardware clock in UTC"
    hwclock --systohc --utc
fi

# Stop any quota file system (if needed)

if grep -E -q -m 1 '(usr|grp)quota' /etc/fstab
then
    echo "${RC}: Setting any quota file system to OFF"
    quotaoff -va
fi

# Save the random number generator, see random(4)

echo "${RC}: Saving random number generator"
echo "    /dev/urandom <-> /etc/random-seed ..."

# Get the pool size from /proc or use a default value
size="$(cat /proc/sys/kernel/random/poolsize)" || size=512

# Save seed file containing the whole entropy pool
dd if=/dev/urandom of=/etc/random-seed count=1 bs=$size
unset -v size
chmod 600 /etc/random-seed

# Try to write a login record (at /var/log/wtmp)
halt -w

# Flush file system buffers, update super block
sync

# Stop FUSE filesystem
if test -x /etc/rc.d/rc.fuse
then
    /etc/rc.d/rc.fuse stop > /dev/null
fi

# Kill all processes, except the one that is currently running
echo "${RC}: Sending the TERM signal to all the processes"
killall5 -15 -o $$
sleep 9

echo "${RC}: Deactivating swap devices"
swapoff -v -a

echo "${RC}: Unmounting local and remote file systems"
umount -v -a -r
sleep 1
sync

echo "${RC}: Remounting root filesystem in read-only mode"
mount -v -n -o remount,ro /

# Wait for completion of all the processes
wait

# Reboot, or halt the system
case $0 in
*.reboot)
    echo "Rebooting ..."
    exec reboot -d -f
    ;;
*)
    exec halt -d -f -p
    ;;
esac

