#! /usr/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# ike72L src/bos/usr/sbin/isakmp/ikedb/mkipsecldap.sh 1.2 
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2012,2018 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 


ATMP=/var/security/ipsec/LDAP
parse_args(){

	while getopts "b:D:w:f" cargs
	do
		case $cargs
		in
		b) #Base DN
		   bflag=1
		   basedn="$OPTARG";;
		D) #Bind DN
		   Dflag=1
		   binddn="$OPTARG";;	
		w) #Bind password
		   wflag=1
		   bindpwd="$OPTARG";;
		*) print "Error in options"
			exit 1;
		esac
	done
}

init_vars(){
# initialize the flags
bflag=0
Dflag=0
wflag=0	

`/usr/bin/ls $ATMP` >/dev/null 2>&1
if [ $? -eq 2 ]
then
	`/usr/bin/mkdir -p $ATMP` >/dev/null 2>&1
	if [ $? -ne 0 ]
	then
		print "Failed to create Directory:$ATMP"
		exit 1;
	fi
fi

}


#Check if the machine is LDAP client, the machine should have been
#configured as LDAP client alredy.

ps -A | grep 'secldapclntd' >/dev/null 2>&1
if [ $? -ne 0 ]
then
	print"Error, secldap daemon is not running"
	exit 1;
fi

init_vars

# parse the command line arguments
parse_args $*

if [ $Dflag -eq 1 ] && [ $wflag -eq 1 ];
then
	# Get the primary LDAP server name
	shostn=`ls-secldapclntd | grep "current ldapserver" |\
		awk -F "=" '{print $2}'`

	# create a ldif file to add parent object

	if [ $bflag -eq 1 ];
	then
		echo "ou=Ip_host,"$basedn >>$ATMP/ipsec.ldif
	else
		echo "ou=Ip_host,cn=aixdata" >>$ATMP/ipsec.ldif
	fi

	echo "ou=Ip_host" >> $ATMP/ipsec.ldif
	echo "objectClass=organizationalUnit" >>$ATMP/ipsec.ldif
	echo "objectClass=top" >>$ATMP/ipsec.ldif

	# Adds the parent object, if its the first time		
	# Ignore the errors from ldapadd, which might happen
	# when the parent object is already added

	/usr/bin/ldapadd -h "$shostn" -D "$binddn" -w "$bindpwd"\
		 -i $ATMP/ipsec.ldif  >/dev/null 2>&1

	/usr/bin/rm $ATMP/ipsec.ldif


	if [ $bflag -eq 1 ];
	then
		echo "ou=ipsec,"$basedn >>$ATMP/ipsec.ldif
	else
		echo "ou=ipsec,cn=aixdata" >>$ATMP/ipsec.ldif
	fi

	echo "ou=ipsec" >> $ATMP/ipsec.ldif
	echo "objectClass=organizationalUnit" >>$ATMP/ipsec.ldif
	echo "objectClass=top" >>$ATMP/ipsec.ldif

	# Adds the parent object, if its the first time
	# Ignore the errors from ldapadd, which might happen
	# when the parent object is already added

	/usr/bin/ldapadd -h "$shostn" -D "$binddn" -w "$bindpwd" \
	 	-i $ATMP/ipsec.ldif  >/dev/null 2>&1

	/usr/bin/rm $ATMP/ipsec.ldif
		exit 0
else
	print "Usage:  mkipsecldap  -D <binddn> -w <bindpwd>  [-b <basedn> ]\n" 
	exit 1

fi