#!/bin/sh
#
# /usr/local/bin/localadduser
# Copyright 2003-2006 Jonas Smedegaard <dr@jones.dk>
#
# $Id: localadduser,v 1.5 2006-08-31 22:51:54 jonas Exp $
#
# Execute adduser noninteractively through sudo
#
# TODO: Check for bad arguments
# TODO: Use getopts to offer help
# TODO: Support overriding options in /etc/local file
#

set -e

verbose=1
#simulate=true
interactive=0

# echo something, but only if in verbose mode
vecho() {
	test -n "$verbose" && echo "$@" >&2
}

u=$1
shift

for chunk in $@; do
	case $chunk in
	    *@*)
		other="${other:+$other }$chunk"
		;;
	    +*)
		phone_area="$chunk"
		;;
	    0*|1*|2*|3*|4*|5*|6*|7*|8*|9*)
		if [ -z "$phone_area" ]; then
			echo "E: Phone number provided without leading area code" >&2
			exit 1
		fi
		if [ -n "$home_phone" ]; then
			echo "E: More than 2 phone numbers provided" >&2
			exit 1
		elif [ -n "$office_phone" ]; then
			office_phone="$phone_area $chunk"
		else
			home_phone="$phone_area $chunk"
		fi
		phone_area=""
		;;
	    *)
		fullname="${fullname:+$fullname }$chunk"
		;;
	esac
done

if [ -n "$phone_area" ]; then
	echo "E: Area code provided without trailing phonenumber" >&2
	exit 1
fi

if [ ! "$interactive" -gt 0 ]; then
	quiet="--quiet"
fi
if [ -n "$fullname$office_phone$home_phone$other" ]; then
	eval $simulate sudo "/usr/sbin/adduser $quiet --disabled-login --gecos \"$fullname,,$office_phone,$home_phone,$other\" \"$u\""
else
	if [ ! "$interactive" -gt 0 ]; then
		echo "E: Not enough info provided to create account for \"$u\"" >&2
		exit 1
	fi
	eval $simulate sudo "/usr/sbin/adduser --disabled-login \"$u\""
fi

eval $simulate localresetpasswd "$u"

#vecho "Account \"$u\" created succesfully! Password is $pass"