
DEAMON_USER="{{daemonUser}}"
HOME_DIRECTORY="{{homeDirectory}}"
SERVICE_DESCRIPTION="{{displayName}}"

if [ -z "${DEAMON_USER}" ]; then
    echo "The User that you want to create has to be set."
    exit 1
fi

if [ -z "${HOME_DIRECTORY}" ]; then
    HOME_DIRECTORY="/Users/${DEAMON_USER}"
fi

# find the next UID and GID that is below 500, so that we can create the service user
# if the user or group already exists, it will use this existing ID and still do the rest. We might have changes to commit.
NEXTUID=$(ID=`dscl . -read "/Users/${DEAMON_USER}" UniqueID 2> /dev/null | awk '{print $2}'` && [ ! -z "$ID" ] && echo "$ID" || dscl . -list /Users UniqueID | awk 'BEGIN{i=0}{if($2>i&&$2<500)i=$2}END{print i+1}')
NEXTGID=$(ID=`dscl . -read "/Groups/${DEAMON_USER}" PrimaryGroupID 2> /dev/null | awk '{print $2}'` && [ ! -z "$ID" ] && echo "$ID" || dscl . -list /Groups PrimaryGroupID | awk 'BEGIN{i=0}{if($2>i&&$2<500)i=$2}END{print i+1}')

echo "Will use '${NEXTUID}' as UserID and '${NEXTGID}' as group ID for User '${DEAMON_USER}'"

#########################################################################################################
dscl . -create "/Users/${DEAMON_USER}" UniqueID "${NEXTUID}"
dscl . -create "/Users/${DEAMON_USER}" PrimaryGroupID "${NEXTGID}"
dscl . -create "/Users/${DEAMON_USER}" NFSHomeDirectory "${HOME_DIRECTORY}"

# Can't login as standard user
dscl . -create "/Users/${DEAMON_USER}" UserShell /usr/bin/false
dscl . -create "/Users/${DEAMON_USER}" RealName "${SERVICE_DESCRIPTION} Administrator"

# Revoke Rights
dscl . -delete "/Users/${DEAMON_USER}" PasswordPolicyOptions
dscl . -delete "/Users/${DEAMON_USER}" AuthenticationAuthority

# Unusable password for standard users
dscl . -create "/Users/${DEAMON_USER}" Password \*
# dscl . -read "/Users/${DEAMON_USER}"
#########################################################################################################

#########################################################################################################
dscl . -create "/Groups/${DEAMON_USER}" PrimaryGroupID "${NEXTGID}"
dseditgroup -o edit -a "${DEAMON_USER}" -t user staff
# Unusable password for standard users
dscl . -create "/Groups/${DEAMON_USER}" Password \*
# dscl . -read "/Groups/${DEAMON_USER}"
#########################################################################################################

# make home directory
mkdir -p "${HOME_DIRECTORY}/Library/Preferences" && chown -R "${DEAMON_USER}:${DEAMON_USER}" "${HOME_DIRECTORY}" || true
