#!/bin/sh
#
# macports-gdm-util assists users in establishing the proper security settings
# to use GDM to support nested and remote X11-based logins.
#
# History: verison 0.1: Initial version
#

#
# MACPORTS_PREFIX should ideally be declared in something like
# /opt/local/share/macports/resources/common.sh along with the functions
# MPLink and MPUnlink and any other functions that are declared useful to
# to share
#
MACPORTS_PREFIX=/opt/local
PAM_FILE=/etc/pam.d/gdm

MPLink()
{
	if [ -f $MACPORTS_PREFIX$1 -a ! -a $2$1 ]; then
		ln -s $MACPORTS_PREFIX$1 $2$1
	fi
}

MPUnlink()
{
	if [ -h $2$1 ]; then
		rm $2$1
	fi
}

MPLaunchctl()
{
	if [ -f /bin/launchctl ]; then
		/bin/launchctl $1 /Library/LaunchDaemons/org.macports.$2.plist
	fi
}

MPEnableLaunchDaemon()
{
	MPLaunchctl "load -w" $1
}

MPDisableLaunchDaemon()
{
	MPLaunchctl "unload -w" $1
}

MGUEnablePAM()
{
	CREDENTIALS=$MACPORTS_PREFIX/etc/gdm/pam
	if [ ! -f $CREDENTIALS ]; then
		cp $CREDENTIALS.sample $CREDENTIALS.conf
	fi
	if [ ! -a $PAM_FILE ]; then
		ln -s $CREDENTIALS.conf $PAM_FILE
	fi
}

MGUDisablePAM()
{
	MPUnlink $PAM_FILE /
}

MGUEnableService()
{
	MPEnableLaunchDaemon gdm
}

MGUDisableService()
{
	MPDisableLaunchDaemon gdm
}

MGUHelp()
{
	echo "macports-gdm-util helps users establish proper pam creditials for"
	echo "GDM so that it can be used to support nested or remote logins over"
	echo "X11."
	echo ""
	echo "enable-pam	link the MacPorts GDM pam creditials file to /etc/pam.d"
	echo "disable-pam	unlink the MacPorts GDM pam creditials from /etc/pam.d"
	echo "help		display this message"
}

if [ -z "$1" ]; then
	echo "usage: $0 enable|disable|help [pam|startupitem]"
	exit 1
fi

case $1 in
	enable	)
		case $2 in
			pam		) MGUEnablePAM	;;
			startupitem	) MGUEnableService	;;
			""		) MGUEnablePAM	; MGUEnableService	;;
		esac
		;;
	disable	)
		case $2 in
			pam		) MGUDisablePAM	;;
			startupitem	) MGUDisableService	;;
			""		) MGUDisablePAM	; MGUDisableService	;;
		esac
		;;
	enable-pam		) MGUEnablePAM	;;
	disable-pam		) MGUDisablePAM	;;
	enable-startupitem	) MGUEnableService	;;
	disable-startupitem	) MGUDisableService	;;
	help	) MGUHelp	;;
	*	) echo "$0: unknown argument: $1"	;;
esac

