#!/bin/bash

#set -x
set -eu
set -o pipefail

rm -f found-dir

case "`uname `" in
	DragonFly*|FreeBSD|NetBSD)
		requiresprovides=true
		;;
	*)
		runlevels=true
		;;
esac

if [ "$runlevels" = true ]
then
	# not all systems that have runlevels, give their runlevel this way...
	case `uname` in
		Linux)
			/usr/bin/who -r | awk ' { print $2 }'
			;;
		DragonFly*|FreeBSD|NetBSD)
			# apparently these guys don't have runlevels...
			echo 'Internal error: BSD systems do not appear to have runlevels' 1>&2
			;;
		*)
			# SunOS 5.7, AIX 5.1, probably most unixes...
			# we use a hardcoded path, because sometimes people have installed
			# a GNU who, and at least the GNU who we are using on SunOS
			# does not understand -r. But the sun who does, as does the AIX who...
			/bin/who -r | awk ' { print $3 } '
			;;
	esac > runlevel

	runlevel="`cat runlevel`"
	echo Looks like the runlevel we need is "$runlevel"
	rm -f runlevel

	fn=S22fallback-reboot

	# AIX likes /etc/rc.d/rc?.d, but not /etc/rc?.d.  So do some (older?)
	# linuxes.  And some systems even like /sbin/rc?.d, though we haven't
	# ported to one yet :)
	for parentdir in /etc /etc/rc.d /sbin
	do
		rcdir="$parentdir"/rc"$runlevel".d
		if [ -d "$rcdir" ]
		then
			echo Installing "$fn" in "$rcdir"
			cp S22fallback-reboot "$rcdir"/"$fn"
			chmod 755 "$rcdir"/"$fn"
			# we touch a file, because /bin/sh cannot portably set a variable
			# inside a loop and count on it being set outside the loop later
			touch found-dir
			break
		fi
	done
fi

if [ "${requiresprovides:-}" = true ]
then
	# this is actually a much better system than the runlevel thing...
	cp S22fallback-reboot /etc/rc.d/fallback-reboot
	chmod 755 /etc/rc.d/fallback-reboot
	touch found-dir
fi

if [ -f found-dir ]
then
	echo Good, we found where to install the rc script 1>&2
	exit 0
else
	echo Dang, we did not find where to install the rc script 1>&2
	exit 1
fi