#!/bin/sh 
#
# Copyright 2003 Sun Microsystems, Inc. All Rights Reserved
#
# PROPRIETARY/CONFIDENTIAL. Use of this product is subject to
# license terms. Copyright 2001 Sun Microsystems, Inc.
# Some preexisting portions Copyright 2001 Netscape Communications Corp.
# All rights reserved.
# 
#
# Usage  ns-keygen password_file fully_qualified_hostname
# Example:
#	./ns-keygen  ../password.txt myhost.iplanet.com
#
# Assumes that NSHOME is Set

if [ $# -ge 2 ]
then 
 	passwd_file=$1
	certDN=$2
else
	echo "ERROR:Incorrect Usage: ./ns-keygen password_file certDN"
	exit
fi

#echo password file name is: $passwd_file
#echo certDN is: $certDN

rm -f key3.db cert7.db secmodule.db random.dat keyid.dat

# Check for  password file

#
# Set umask for best security
#
umask 077 

#
# Create some "random" data. 
#
ps -ale >>random.dat
date >>random.dat
netstat -a >>random.dat

if [ ! -s $passwd_file ]
then
	echo "Error:Password file is missing."
	exit 1
fi

#
# Create a key database file with the password supplied
#
$NSHOME/bin/slapd/admin/bin/keyutil -N -d . -w $passwd_file 
RC=$?
if [ $RC != 0 ]
then 
	echo "Error:Unable to create key database."
	exit 1
fi

#
# Create a new private/public key pair
#
$NSHOME/bin/slapd/admin/bin/keyutil -G -d . -w $passwd_file -f random.dat -z keyid.dat
RC=$?
if [ $RC != 0 ]
then 
	echo "Error:Unable to create private/public key pair."
	exit 1
fi

#
# Create and sign a self-signed certificate for this
# server using the server name
#
$NSHOME/bin/slapd/admin/bin/certutil -S -z keyid.dat -s "$certDN" -x -t u,, \
 -m 0 -v 60 -d . -n Server-Cert -f $passwd_file
RC=$?
if [ $RC != 0 ]
then 
	echo "Error:Unable to create the cert."
	exit 1
fi

hostname=`uname -n`

#
# Copy the key/cert db & password file to the correct place.
#
cp key3.db $NSHOME/alias/slapd-$hostname-key3.db
RC=$?
if [ $RC != 0 ]
then 
	echo "Error:Key Database could not be copied"
	exit 1
fi

cp cert7.db $NSHOME/alias/slapd-$hostname-cert7.db
RC=$?
if [ $RC != 0 ]
then 
	echo "Error:Cert Database could not be copied"
	exit 1
fi
cp $passwd_file $NSHOME/alias/slapd-$hostname-password.txt
RC=$?
if [ $RC != 0 ]
then 
	echo "Error:password file could not be copied"
	exit 1
fi
# Test the new location for the files.

#
# Cleanup
rm -f random.dat keyid.dat 

#
# End
#
