#!/bin/ksh -u
# Bring the memberlist of a MailToUrl domain file.
# This is when it is used by exim.
# The list of users is the standard input to this script.
# The name of the file to update is the argument to this script.
# SCCS: @(#)MailToUrlUsers	1.1 04/02/09 13:55:00
# Author: Alain D D Williams  <addw@phcomp.co.uk> of Parliament Hill Computers, http://www.phcomp.co.uk.
# Copyright (C) the Author March 2009, all rights reserved.
# This script is licensed under the GPL version 3.

# You will probably use it in a cron job like something this:
#	/usr/local/mailman/stalbans-go/bin/list_members chat | MailToUrlUsers /etc/exim/file_domains/go

# Quite simple really, preserve any lines starting '.', remove the rest,
# update the file if anything has changed.

PROGNAME=${0##*/}

Extra=

# Print a usage message
function Usage {
	ec=0
	[[ ${1:-} != "" ]] && echo "$1" >&2 && ec=2
	cat <<-! >&2
	Update the list of authorised users in a MailToUrl domain file.
	A list of email addresses will be read from stdin
	Usage: $PROGNAME [options] FileToUpdate
	-e file	Extra users listed in this file
	-x	eXplain - help message
	--help	help message
	Version: 1.1 04/02/09
	!

	exit $ec
}

# Echo the arguments to stderr & die
function Die {
	echo "$PROGNAME: $*" >&2
	exit 2
}

# Parse options, recognise --help
while	OPTIND=1
	if [[ $# != 0 && $1 = --help ]]
	then	opt=x	# --help is -x
	else	getopts e:x opt
	fi
do	case "$opt" in
	e)	Extra=$OPTARG ;;
	x)	Usage	;;
	*)	Usage "Unknown option '$1'"	;;
	esac
	shift $((OPTIND - 1))
done


[[ $# = 0 ]] && Usage "FileToUpdate not specified"

file=$1
new=$file.new

[[ ! -r $file ]] && Die "I can't read $file"

# This might look long winded & pointless but it preserves the ownership and permissions:
cp -a $file $new || Die "I can't create the new file: $new"
> $new || Die "Can't truncate $new"

# Extract control line
grep '^\.' $file > $new || Die "I can't extract control lines from $file"

# Append the list of users - from stdin. Sort for easy comparison
(
  cat
  [[ $Extra != '' ]] && cat $Extra
) | sort >> $new || Die "I can't append the list of user email addresses"

# Compare old & new. Update if different
if cmp -s $file $new
then	rm -f $new || Die "I can't remove the temp file"
else	mv -f $new $file || Die "I can't replace $file with $new"
fi

# end
