#!/bin/bash

. ./fusion-sys.cfg

# Was previous step completed?
if [ ! -f installed.prereqs ]; then
    echo "Prerequisites were not properly prepared" >&2
    exit 1
fi

# Is Users and Groups already installed?
if [ -f installed.usergroups ]; then
    echo "Users and Groups already installed - skipping..."
    exit 0
fi

# ================
# Users and Groups
# ----------------

echo "Adding users and groups..."
"$useraddbin" "$nagiosuser"
"$groupaddbin" "$nagiosgroup"
if [ "$dist" = "suse11" ]; then
    "$usermodbin" -A "$nagiosgroup" "$nagiosuser"
    "$usermodbin" -A "$nagiosgroup" "$apacheuser"
else
    "$usermodbin" -a -G "$nagiosgroup" "$nagiosuser"
    "$usermodbin" -a -G "$nagiosgroup" "$apacheuser"
fi

# Make sure user exists
if ! grep -q "^$nagiosuser:" /etc/passwd; then
    echo "ERROR: User '$nagiosuser' was not created - exiting." >&2
    exit 1
fi

# Make sure group exists
if ! grep -q "^$nagiosgroup:" /etc/group; then
    echo "ERROR: Group '$group' was not created - exiting." >&2
    exit 1
fi

# If nagios user was created before this install, check the homedir
homedir=$(getent passwd "$nagiosuser" | cut -d : -f 6)
if [ ! -d "$homedir" ]; then
    if ! "$mkdirbin" -p "$homedir"; then
        echo "ERROR: Unable to create home directory - exiting." >&2
        exit 1
    else
        chown "$nagiosuser":"$nagiosgroup" "$homedir"
    fi
fi

echo "Users and Groups installed OK"
touch installed.usergroups