#!/bin/sh
#
# /usr/local/bin/localnsrequest
# Copyright 2001, 2002 Jonas Smedegaard <dr@jones.dk>
#
# $Id: localnsrequest,v 1.4 2002-08-29 11:06:50 jonas Exp $
#
# Send requests regarding domain registrations to registrars
#
# TODO
#  * Loop through all options *before* sending any mail, to exit
#    on error with no half-done batch
#  * Look for password in home, similar to mysql my.cnf.
#  * Clean up the mess of handles being both e.g. spiff and radar
#

set -e

prg=$(basename $0)
copyright="(C) 2002 Jonas Smedegaard <dr@jones.dk>"

usage="$prg, $copyright

Usage: $prg <handle> reg|redel <domain> [<otherdomain> ...]"

if [ $# \< 3 ]; then
	echo "Too few parameters!"
	echo
	echo "$usage"
	exit 1
fi
handle=$1
shift
action=$1
shift

if [ -z "$handle" ]; then
	echo "Error: Missing handle!"
	echo
	echo "$usage"
	exit 1
fi

BCC=""
[ -n "$EMAIL" ] && BCC="-c $EMAIL"

for DOMAIN in $@; do
	case $DOMAIN in
	    *.dk)
		dir='/etc/local-COMMON/DK-Hostmaster'
		TO="hostmaster@dk-hostmaster.dk"
		case $action in
		    reg)
			file=domain.3.00.dansk.txt-$handle
			;;
		    redel)
			file=redelegation.3.00.dansk.txt-$handle
			;;
		    *)
			echo "Unsupported action: \"$action\"!"
			echo
			echo "$usage"
			echo
			echo "Supported actions for this TLD: reg redel"
			exit 1
			;;
		esac

		if [ ! -f $dir/$file ]; then
			echo "Error: File \"$dir/$file\" doesn't exist!"
			echo "Did you use a valid handle?"
			echo
			echo "$usage"
			exit 1
		fi

		sed -e "s/{DOMAIN}/$DOMAIN/g" $dir/$file \
			| mail -s "$action $DOMAIN ($handle)" -a "Content-Type: TEXT/PLAIN; charset=ISO-8859-1" $BCC -e $TO
		;;
	    *.com|*.org|*.net)
		dir='/etc/local-COMMON/TotalRegistrations'
#		TO="register@totalregistrations.com"
		file=email-$handle
		case $action in
		    reg)
			ACTION=N
			;;
		    redel)
			ACTION=T
			;;
		    *)
			echo "Unsupported action: \"$action\"!"
			echo
			echo "$usage"
			echo
			echo "Supported actions for this TLD: reg redel"
			exit 1
			;;
		esac
		echo -n "Enter TotalRegistrations password: "
		read -s PASSWD
		echo
		[ -z "$PASSWD" ] && {
			echo "No password provided. Exiting..."
			exit 1
		}

		if [ ! -f $dir/$file ]; then
			echo "Error: File \"$dir/$file\" doesn't exist!"
			echo "Did you use a valid handle?"
			echo
			echo "$usage"
			exit 1
		fi
		account=`cat $dir/$file | grep '^11a\.' | sed -e 's/.*:\W\([[:alnum:]]\+\)/\1/'`
		TO=$account@totalregistrations.com

		sed -e "s/{DOMAIN}/$DOMAIN/g" -e "s/{ACTION}/$ACTION/g" -e "s/{PASSWD}/$PASSWD/g" $dir/$file \
			| mail -s "$action $DOMAIN ($handle)" -a "Content-Type: TEXT/PLAIN; charset=ISO-8859-1" -e $TO
#			| gpg -ea -r $TO | mail -s "$action $DOMAIN ($handle)" -a "Content-Type: TEXT/PLAIN; charset=ISO-8859-1" -e $TO
		;;
	    *)
		echo "Unsupported domain: \"$DOMAIN\"!"
		echo
		echo "$usage"
		exit 1
		;;
	esac
done