#! /bin/sh

# create a template user

export PATH=/bin:/usr/bin:/sbin:/usr/sbin

# arbitrary uid
N_UID=501

# arbitrary gid
N_GID=501

# user name
N_USERNAME="$1"

# home
N_HOME="/var/${N_USERNAME}"

# system default user home template
SYSHOMETEMPLATE="/System/Library/User Template/English.lproj"

# make sure the uid and gid are available
while [ true ]; do
    user="`niutil -read . /users/uid=${N_UID} 2>/dev/null`"

    if [ -z "${user}" ]; then
	break
    fi

    N_UID=$((${N_UID} + 1));
done

while [ true ]; do
    group=`niutil -read . /groups/gid=${N_GID} 2>/dev/null`

    if [ -z "${group}" ]; then
	break
    fi

    N_GID=$((${N_GID} + 1));
done

# create user
niutil -create . "/users/${N_USERNAME}" 2>/dev/null

if [ $? -ne 0 ]; then
    logger -is Creation of ${N_USERNAME} failed.
    exit 2
fi

niutil -createprop . "/users/${N_USERNAME}" uid ${N_UID} 2>/dev/null
niutil -createprop . "/users/${N_USERNAME}" gid ${N_GID} 2>/dev/null
niutil -createprop . "/users/${N_USERNAME}" passwd "*" 2>/dev/null
niutil -createprop . "/users/${N_USERNAME}" name ${N_USERNAME} 2>/dev/null
niutil -createprop . "/users/${N_USERNAME}" home ${N_HOME} 2>/dev/null
niutil -createprop . "/users/${N_USERNAME}" _writers_passwd ${N_USERNAME}
niutil -createprop . "/users/${N_USERNAME}" _writers_hint ${N_USERNAME}
niutil -createprop . "/users/${N_USERNAME}" realname "Template User"
niutil -createprop . "/users/${N_USERNAME}" shell /bin/tcsh

# create group
niutil -create . "/groups/${N_USERNAME}"

# destroy user if group creation fails
if [ $? -ne 0 ]; then
    niutil -destroy . "/users/{N_USERNAME}"
    logger -is Creation of group ${N_USERNAME} failed.
    exit 2
fi

niutil -createprop . "/groups/${N_USERNAME}" name ${N_USERNAME}
niutil -createprop . "/groups/${N_USERNAME}" gid ${N_GID}
niutil -createprop . "/groups/${N_USERNAME}" passwd "*"
niutil -createprop . "/groups/${N_USERNAME}" users ${N_USERNAME}

# make home directory
mkdir -m 0700 -p ${N_HOME}
ditto -rsrcFork "${SYSHOMETEMPLATE}" "${N_HOME}"

if [ $? -ne 0 ]; then
    niutil -destroy . "/users/${N_USERNAME}"
    niutil -destroy . "/groups/${N_USERNAME}"
    logger -is Creation of ${N_HOME} failed.
    exit 2
fi

chown -R ${N_USERNAME}:${N_USERNAME} ${N_HOME}

logger -i Creation of template user ${N_USERNAME} succeeded.

exit 0
