#!/bin/sh
# Portable System Interface Copyright (c) 1997-1998 Tycho Softworks.
# $Id: instinit 1.3 Fri, 23 Oct 1998 22:41:02 -0400 dyfet $

run=/etc/rc.d
levels=""
prefix=$1
shift
base=`basename $1`
itype='.init'
suffix=''

source=$1$itype
shift

if test -d /etc/init.d ; then
	run=/etc
else
	if test -d /etc/rc.d/init.d ; then
		prefix=$prefix/rc.d
	fi
fi

if test ! -d $run ; then
	if test -d /etc/rc.d/rc.local ; then
		run=/etc/rc.d/rc.local
		install -d $prefix/rc.d/rc.local
		install -o root -m 0700 $source $prefix/rc.d/rc.local/rc.$base
	fi
	exit 0
fi

if test -d $run/init.d ; then
	levels=$run
	init='../init.d/'$base$suffix
	run=$run/init.d
	target=$base$suffix
else
	target='rc.'$base
	levels='false'
fi

echo 'Adding '$target' to '$run
install -d $prefix/init.d
install -o root -m 0700 $source $prefix'/init.d/'$target

if [ -z "$levels" ] ; then
	exit 0
fi

initial=$1
shift
inc=$1
shift

list="$*"
if test -z "$list" ; then
	list="9 8 7 6 5 4 3 2 1"
fi

for level in $list ; do
	runlvl=$levels'/rc'$level'.d'
	runinit=$prefix'/rc'$level'.d'
	
	if [ ! -d $runlvl ] ; then
		continue
	fi
	cd $runlvl
	# echo "test" >S00$base

	case $initial in
	%http)
		if test -f S??*http ; then
			initial="*http"
		fi
		if test -f S??httpd ; then
			initial="httpd"
		fi
		;;
	%rpc)
		if test -f S??portmap ; then
			initial="portmap"
		fi
		if test -f S??rpcinit ; then
			initial="rpcinit"
		fi
		if test -f S??rpc ; then
			initial="rpc"
		fi
		;;
	%sound)
		if test -f S??sound ; then
			initial="sound"
		fi
		;;		
	%net)
		if test -f S??network ; then
			initial="network"
		fi
		if test -f S??tcp ; then
			initial="tcp"
		fi
		;;
	%inet)
		if test -f S??network ; then
			initial="network"
		fi
		if test -f S??inet ; then
			initial="inet"
		fi
		if test -f S??tcp ; then
			initial="tcp"
		fi
		if test -f S??named ; then
			initial="named"
		elif test -f S??dns ; then
			initial="dns"
		fi
		;;
	esac
	
	other=`echo S??$initial`
	if test ! -f "$other" ; then
		continue
	fi
	count=`echo $other | sed s/$initial// | sed s/^S//`
	count=`echo "$count + $inc" | bc`
	target='S'$count$base
	echo 'Adding '$target' to '$runlvl
	install -d $runinit
	cd $runinit
	rm -f S*$base
	ln -s $init $target
done
		
	

