#!/bin/bash

nameRegEx='^[A-Z,a-z,0-9,\.,-]+$'
lockfile="/tmp/""$(echo $0 | rev | cut -f 1 -d '/' | rev)"

function helptext {
    echo "$0 username [ userid ]"
}

# match email against regex and create shortname from email ID.
if [ ! -z "$1" ] && [[ "$1" =~ $nameRegEx ]]; then
    username="$(echo $1)"
    if getent passwd "$username"; then
        echo User already exists!
        exit 1;
    fi
elif [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    helptext;
    exit 0;
else
    echo Need an username.
    helptext
    exit 1;
fi

# Create a new user ID.
if [ -z "$2" ]; then
    newuserid="$(($(getent passwd | sort -k 3 -n -t ':' | tail -n 1 | cut -f 3 -d ':') + 1))"
else
    if id "$newuserid" &>/dev/null; then
        echo "User id $newuserid already exist!"
        exit 2
    else
        newuserid="$2"
    fi
fi

printf "Username: %s\nID: %s\n\nReady to add? [YES/no]   " "$username" "$newuserid"


mkdir "$lockfile" 2>/dev/null
if [ "$?" -eq 0 ]; then
    read answer
    if [ "$answer" == "YES" ]; then
        file="/etc/openldap/users.d/$username.ldif"
        cp /opt/aninix/Password/sample-user.ldif "$file"
        line="$(grep -E '^uid: ' "$file")"; sed -i "s/$line/uid: $username/" "$file"
        line="$(grep -E '^dn: ' "$file" | cut -f 2 -d ' ' | cut -f 1 -d ',')"; sed -i "s/$line/uid=$username/" "$file"
        line="$(grep -E '^homeDirectory: ' "$file")"; sed -i "s#$line#homeDirectory: /home/$username/#" "$file"
        line="$(grep -E '^cn: ' "$file")"; sed -i "s/$line/cn: $username/" "$file"
        line="$(grep -E '^mail: ' "$file")"; sed -i "s#$line#mail: ircs://aninix.net:6697/$username#" "$file"
        line="$(grep -E '^uidNumber: ' "$file")"; sed -i "s/$line/uidNumber: $newuserid/" "$file"
        ldapadd -D 'cn=root,dc=aninix,dc=net' -W -f "$file"
        ldap-resetpass "$username"
    fi
    rmdir "$lockfile"
    exit 0;
else
    echo "Cannot add -- locked."
    exit 1;
fi