#!/bin/sh
set -e

PREFIX="MACPORTS_PREFIX"

NAME=netatalk
SCRIPTNAME=/etc/init.d/$netatalk

# Set defaults. Please change these options in netatalk.conf.
AFPD_UAMLIST="-U uams_dhx.so"
AFPD_GUEST=nobody
AFPD_MAX_CLIENTS=50
CNID_METAD_RUN=yes
CNID_METAD_ARGS="-h 127.0.0.1 -p 4700"
ATALK_MAC_CHARSET='MAC_ROMAN'
ATALK_UNIX_CHARSET='LOCALE'
ATALK_BGROUND=no

# Read in netatalk configuration.
if [ -f "$PREFIX/etc/netatalk/netatalk.conf" ]; then
	. "$PREFIX/etc/netatalk/netatalk.conf"
fi

# Start Netatalk servers.
atalk_startup() {
	# prepare startup of file services
	if [ "x${CNID_METAD_RUN}" = "xyes" -a -x "$PREFIX/sbin/cnid_metad" ] ; then
	        printf "   cnid_metad ..."
		"$PREFIX/sbin/cnid_metad" $CNID_METAD_ARGS
		printf " Done.\n"
	fi
	
	if [ "x$AFPD_RUN" = "xyes" ]; then
	    printf "   afpd ..."
	    "$PREFIX/sbin/afpd" $AFPD_UAMLIST -g $AFPD_GUEST -c $AFPD_MAX_CLIENTS
	    printf " Done.\n"
	fi
}

case "$1" in
	start)
		if test "x${ATALK_BGROUND}" = "xyes"; then
			atalk_startup >/dev/null &
		else
			echo "Starting Netatalk services..."
			atalk_startup
			echo "Done."
		fi
	;;

	stop)
                AFP_PID=`ps aux | grep -v awk | awk '/^root.*afpd/ {print $2}'`
		if [ "x$AFP_PID" != "x" ] ; then
		    kill $AFP_PID
		fi
                CNID_PID=`ps aux | grep -v awk | awk '/^root.*cnid_metad/ {print $2}'`
		if [ "x$CNID_PID" != "x" ] ; then
		    kill $CNID_PID
		fi
   	;;
	
	restart)
		$0 force-reload
	;;

	force-reload)
		$0 stop
		sleep 2
		$0 start
	;;
  
	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 1
	;;
esac
