#!/bin/bash

# Directory where nut is installed
DIR="/usr/local/nut_upsmon"

# User/Group name to create and assign permissions to
NAME="nut_upsmon"

# Secondary group to own installation files to
GROUP="admin"


# Ensure that there's a user for NUT to use

# Check to see if the user exists or not
nicl . -read /users/${NAME} >/dev/null 2>&1
if [ $? != 0 ]; then

    echo "User ${NAME} does not exist; creating..."

    # delete any pre-existing group with our name (shouldn't happen)
    nicl . -delete /groups/${NAME} >/dev/null 2>&1

    # Find the next shared UID/GID that's between 100 and 500
    lastid=`(nireport . /users uid ; nireport . /groups gid) | sort -n | uniq | egrep -v '^([0-9]{1,2}|[5-9][0-9]{2,}|[0-9]{4,})[^0-9]+' | tail -1`
    id="`expr $lastid + 1`"

    # in the case that there is no ID over 100 to come after, just start at 200
    if [ ${id} -lt 100 ]; then
	id=200
    fi

    # create new group
    echo "Creating group ${NAME} with GID $id"
    nicl . -create /groups/${NAME}
    nicl . -createprop /groups/${NAME} gid ${id}
    nicl . -createprop /groups/${NAME} passwd '*'
    echo "niutil: group '${NAME}' added."

    echo "Creating user ${NAME} with UID ${id}"
    nicl . -create /users/${NAME}
    nicl . -createprop /users/${NAME} uid ${id}
    nicl . -createprop /users/${NAME} gid ${id}
    nicl . -createprop /users/${NAME} passwd '*'
    nicl . -createprop /users/${NAME} change 0
    nicl . -createprop /users/${NAME} expire 0
    nicl . -createprop /users/${NAME} realname "NUT UPS Monitor"
    nicl . -createprop /users/${NAME} home "${DIR}"
    nicl . -createprop /users/${NAME} shell '/usr/bin/false'
    nicl . -createprop /users/${NAME} _writers_passwd "${NAME}"
    echo "niutil: user '${NAME}' added."
else
    echo "User '${NAME}' already exists; not creating it again"
fi


echo "Setting permissions for ${DIR} to ${NAME}:${GROUP}:"

chown -R ${NAME}:${GROUP} "${DIR}"
chmod -R u+rw,g-w,o-w "${DIR}"

exit 0
