#!/bin/sh

GROUP="mail"
SPOOL="/var/spool/mail"
PREVIEW=""

function syntax {
	printf "Usage: %s [COMMANDS] [OPTIONS]\n" `basename $0`
	echo
	echo "Commands:"
	printf -- " setgid\t\t\t\tMake Procmail sgid '$GROUP'\n"
	echo
	echo "Options:"
#	printf -- " -e, --execute\t\t\tMake Procmail sgid '$GROUP'\n"
	printf -- " -g, --group GROUP\t\tSelect GROUP with COMMAND\n"
	printf -- " -h, --help\t\t\tThis help text\n"
	printf -- " -W, --Windows\t\t\tPREVIEW actual Windows commands without executing\n"
}
function welcome {
	echo
	echo "You have finished installing Procmail. If you want the program to be used "
	echo "by non-privileged users, you will have to take some extra steps. You will "
	echo "need the following:"
	echo
	echo "1. Create a separate group for mail-users, by default '$GROUP'. "
	echo "2. Make group '$GROUP' the owner of the mail spool ($SPOOL). "
	echo "3. Make the Procmail executables sgid '$GROUP'. "
	echo
	echo "If you want this done automatically, re-start this script with the 'setgid'"
	echo "command:"
	echo
	printf -- "\tprocmail-config setgid\n"
	echo
	echo "Use the --help option for available configuration options. "
}
function groupadd {
	if [[ `getent group "$1"` ]]; then
		return
	elif [ $PREVIEW ]; then
		printf -- 'Windows: net localgroup "%s" /add\n' "$1"
		printf -- 'Cygwin: mkgroup -l -g "%s" >>/etc/group\n' "$1"
	else
		net localgroup "$1" /add >/dev/null
		mkgroup -l -g "$1" >>/etc/group
	fi
}

command=""

function set_group {
	if ! [[ `getent group "$1"` ]]; then
		echo "$1: No such group."
		exit 1
	fi
	GROUP="$1"
}

while [ "$1" ]; do
	case "$1" in
		-e|--execute)			# depreciated
			command="setgid"
			;;
		-g|--group)
			set_group "$2"
			shift
			;;
		-h|--help)
			syntax
			exit
			;;
		-W|--windows)
			echo
			PREVIEW="yes"
			;;
		-*)
			echo "$1: No such option."
			echo
			syntax
			exit 1
			;;
		setgid)
			command="$1"
			;;
	esac
	shift
done

function do_setgid {
	groupadd "$GROUP"
	if ! [ $PREVIEW ]; then
		chgrp "$GROUP" $SPOOL /usr/bin/procmail.exe /usr/bin/lockfile.exe
		chmod g+w $SPOOL
		chmod g+s /usr/bin/procmail.exe /usr/bin/lockfile.exe
	fi
}

if [ "$command" ]; then
	do_$command
else
	welcome
fi
