#!/bin/sh

# PROVIDE: scponlyc
# REQUIRE: LOGIN cleanvar
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable scponly:
# scponlyc_enable (bool):		Set to "NO" by default.
#					Set it to "YES" to enable scponly
# scponlyc_shells (str):		Set to "/etc/shells" by default.
# scponlyc_passwd (str):		Set to "/etc/passwd" by default.

. /etc/rc.subr

scponlyc_shells="${scponlyc_shells:-/etc/shells}"
scponlyc_passwd="${scponlyc_passwd:-/etc/passwd}"

name="scponlyc"
rcvar=scponlyc_enable

start_cmd="scponlyc_startcmd"
stop_cmd="scponlyc_stopcmd"

required_files="$scponlyc_shells $scponlyc_passwd"

scponlyc=%%PREFIX%%/sbin/scponlyc

make_devfs() {
	# $1 is the user name whose home directory needs a minimal
	# devfs created. If ~/dev exists, it will be deleted.

	eval DEV="~$1/dev"
	if /sbin/mount | grep "${DEV}" >/dev/null 2>&1; then
		/sbin/umount "${DEV}" 2>/dev/null
	fi
	/bin/rmdir "${DEV}" || err 1 "Unable to remove $DEV"
	/bin/mkdir -p "${DEV}"
	devfs_domount "${DEV}"
	if devfs_init_rulesets; then
		devfs_apply_ruleset "devfsrules_hide_all" "${DEV}" && \
		devfs_apply_ruleset "devfsrules_unhide_basic" "${DEV}" || \
		/sbin/umount "${DEV}" 2>/dev/null
	fi
}

users_configured() {

	if [ `/usr/bin/grep -c "/scponlyc$" ${scponlyc_shells} 2>/dev/null` -ne 1 ]; then
		exit 1
	fi
}

scponlyc_startcmd() {

	users_configured

	/usr/bin/grep "^[^#]*:.*:.*:.*:.*:.*:${scponlyc}$" ${scponlyc_passwd} |
		/usr/bin/awk -F: {'print $1'} |
		while read USER; do
			/bin/echo "${USER}/dev"
			make_devfs "${USER}"
		done
}

scponlyc_stopcmd() {

	users_configured

	/usr/bin/grep "^[^#]*:.*:.*:.*:.*:.*:${scponlyc}$" ${scponlyc_passwd} |
		/usr/bin/awk -F: {'print $1'} |
		while read USER; do
			/bin/echo "${USER}/dev"
			eval DEV="~${USER}/dev"
			/sbin/umount ${DEV} 2>/dev/null
		done
}

load_rc_config $name
run_rc_command "$1"
