#!/bin/sh

usrPath="/usr/local/natinst/share/NIAuth"
varPath="/run/natinst/niauth"
enableFilePath="$varPath/enable_nss_pam"
dbPath="/etc/natinst/share/niauth"

progName="niauth"

startDaemon(){
	# Create the database directory with the proper permissions. (If the
	# directory already exists, retouch its permissions.)
	if [ -d "$dbPath" ]; then
		dir="$dbPath"
	elif ! dir=`mktemp -d -p /etc/natinst/share`; then
		echo "Couldn't create temporary directory for NIAuth"
		exit 1
	fi

	if ! chown webserv:ni "$dir"; then
		echo "Couldn't set NIAuth database directory owner"
		exit 1
	fi
	if ! chmod 700 "$dir"; then
		echo "Warning: Couldn't set NIAuth database directory permissions"
	fi

	# Atomically move the database directory into place if it was just created.
	if [ ! -d "$dbPath" ]; then
		if ! mv "$dir" "$dbPath"; then
			echo "Couldn't create NIAuth database directory"
			exit 1
		fi
	fi

	mkdir -p "$varPath"

	echo -n "Starting NIAuth: "
	start-stop-daemon --start -x $usrPath/niauth_daemon -- -start -timeout 30
	echo "1" > "$enableFilePath"
	echo "done"
}

stopDaemon(){
	mkdir -p "$varPath"

	echo -n "Stopping NIAuth: "
	echo "0" > "$enableFilePath"
	start-stop-daemon --stop --quiet --retry 30 -x $usrPath/niauth_daemon
	echo "done"
}

case "$1" in
  start)
        startDaemon
        ;;
  stop)
        stopDaemon
        ;;
  force-reload|restart|reload)
        stopDaemon
        startDaemon
        ;;
  *)
        echo "Usage: $progName {start|stop|restart|reload|force-reload}" >&2
        exit 1
        ;;
esac

exit 0

