#!/bin/sh

# $Id: startsrv.sh,v 1.7 1996/08/23 23:51:09 vixie Exp $

# Copyright (c) 1996 by Internet Software Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
# ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
# CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
# PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.

default_options='-b 9600 -w 8 -p none'
default_sock_prot='ug=rw,o='
default_sock_owner='root.system'
default_log_prot='u=rw,g=r,o='

for host
do
	echo -n "startsrv($host):"
	#
	# kill any existing ttysrv on this port
	#
	[ -f /usr/local/rtty/pid/$host ] && {
		pid=`cat /usr/local/rtty/pid/$host`
		echo -n " oldpid=$pid"
		while ps w$pid >/tmp/startsrv$$ 2>&1
		do
			grep -s ttysrv /tmp/startsrv$$ && {
				echo -n " killed"
				kill $pid
				sleep 1
			} || {
				break
			}
		done
		rm /usr/local/rtty/pid/$host /tmp/startsrv$$
	}
	#
	# start up a new one
	#
	if [ -s /usr/local/rtty/opt/${host}.srv ]; then
		options=`cat /usr/local/rtty/opt/${host}.srv`
	elif [ -s /usr/local/rtty/opt/DEFAULT.srv ]; then
		options=`cat /usr/local/rtty/opt/DEFAULT.srv`
	else
		options="$default_options"
	fi

	if [ -s /usr/local/rtty/prot/${host}.sock ]; then
		sock_prot=`cat /usr/local/rtty/prot/${host}.sock`
	elif [ -s /usr/local/rtty/prot/DEFAULT.sock ]; then
		sock_prot=`cat /usr/local/rtty/prot/DEFAULT.sock`
	else
		sock_prot="$default_sock_prot"
	fi

	if [ -s /usr/local/rtty/owner/${host}.sock ]; then
		sock_owner=`cat /usr/local/rtty/owner/${host}.sock`
	elif [ -s /usr/local/rtty/owner/DEFAULT.sock ]; then
		sock_owner=`cat /usr/local/rtty/owner/DEFAULT.sock`
	else
		sock_owner="$default_sock_owner"
	fi

	if [ -s /usr/local/rtty/prot/${host}.log ]; then
		log_prot=`cat /usr/local/rtty/prot/${host}.log`
	elif [ -s /usr/local/rtty/prot/DEFAULT.log ]; then
		log_prot=`cat /usr/local/rtty/prot/DEFAULT.log`
	else
		log_prot="$default_log_prot"
	fi

	rm -f /usr/local/rtty/sock/$host
	# braces are needed due to obscure bug in ash
	# they won't hurt other systems
	{ /usr/local/rtty/bin/ttysrv $options \
		-t /usr/local/rtty/dev/$host \
		-s /usr/local/rtty/sock/$host \
		-l /usr/local/rtty/log/$host & }
	echo $! >/usr/local/rtty/pid/$host
	echo -n " newpid=$!"
	sleep 1
	chmod $sock_prot /usr/local/rtty/sock/$host
	chown $sock_owner /usr/local/rtty/sock/$host
	chmod $log_prot /usr/local/rtty/log/$host
	echo " done."
done

exit
