#!/bin/sh
#
# $NetBSD: random_seed,v 1.4 2012/12/14 18:42:25 apb Exp $
#

# PROVIDE: random_seed
# REQUIRE: mountcritlocal
# BEFORE: securelevel
# BEFORE: bootconf
# KEYWORD: shutdown
#
# The "BEFORE: securelevel" is a real dependency, in that
# this script won't work if run after the securelevel is changed.
#
# The "BEFORE: bootconf" is intended to cause this to
# be the first script that runs after mountcritlocal.

$_rc_subr_loaded . /etc/rc.subr

name="random_seed"
rcvar=$name
start_cmd="random_load"
stop_cmd="random_save"

random_file=${random_file:-/var/db/entropy-file}

fs_safe()
{
	#
	# Enforce that the file's on a local filesystem.
	# Include only the types we can actually write.
	#
	fstype=$(df -G "$1" |
		while read line ; do
		    set -- $line
		    if [ "$2" = "fstype" ]; then echo "$1" ; break ; fi
		done )
	case $fstype in
	    ffs)
		return 0
		;;
	    lfs)
		return 0
		;;
	    ext2fs)
		return 0;
		;;
	    msdos)
		return 0;
		;;
	    v7fs)
		return 0;
		;;
	 esac
	 return 1
}

random_load()
{
	if [ -f $random_file ]; then

		if ! fs_safe "${random_file}"; then
			return 1
		fi

		set -- $(ls -ldn "${random_file}")
		st_mode="$1" # should be "-rw-------"
		st_uid="$3"  # should be "0" for root

		# The file must be owned by root,
		if [ "$st_uid" != "0" ]; then
			return 1
		fi
		# and root read/write only.
		if [ "$st_mode" != "-rw-------" ]; then
			return 1
		fi

		if rndctl -L "${random_file}"; then
			echo "Loaded entropy from disk."
		fi
		
	fi
}

random_save()
{
	oum=$(umask)
	umask 077

	rm -Pf "${random_file}"

	if ! fs_safe "${random_file}"; then
		return 1
	fi

	if rndctl -S "${random_file}"; then
		echo "Saved entropy to disk."
	fi
}


load_rc_config $name
run_rc_command "$1"
