#!/bin/bash

username=$1
group=$2
current_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ini="$current_dir/scripts.ini"
ldap_password=$(awk '/ldap_password/ {print $2}' $ini)
dc=$(awk '/dc/ {print $2}' $ini)
cn="$(awk '/cn/ {print $2}' $ini),$dc"
group_ou="$(awk '/group_ou/ {print $2}' $ini),$dc"
users_ou="$(awk '/users_ou/ {print $2}' $ini),$dc"

ldiftmp="/tmp/ldapmemberadd.ldif"
ldiftemplate="$current_dir/add_member.ldif"

if [ ! -f $ldiftemplate ]
then
	echo "Template file not found in $ldiftemplate"
	exit 0
fi

if [ -z "$username" ]
then
	echo "Empty username. usage: add_member 'username' 'group'"
	exit 0
fi

if [ -z "$group" ]
then
        echo "Empty group. usage: add_member 'username' 'group'"
        exit 0
fi

TEXT=$(cat $ldiftemplate)
TEXT=${TEXT//\{LOGIN\}/$username}
TEXT=${TEXT//\{GROUP\}/$group}
TEXT=${TEXT//\{GROUP_OU\}/$group_ou}
TEXT=${TEXT//\{PEOPLE_OU\}/$users_ou}

echo "$TEXT" > $ldiftmp
ldapmodify -D $cn -w $ldap_password -f $ldiftmp > /dev/null 2>&1
if [ $? -gt 0 ]
then
	echo 'Error'
else
	echo 'Success!'
fi
#rm $ldiftmp
