#/bin/sh
#
# Generate a self-sighed PEM certificate
#
# Parameter: name of the pem file
# Example: "makepem /tmp/slapd.pem"
#
if [ "$1" == "" ]; then
  echo "Please supply at least a PEM file name!"
  echo "Usage:"
  echo "  $0 /path/to/filename.pem"
  echo "or"
  echo "  $0 /path/to/filename.pem my.host.name"
  echo "In the last example, no questions asked! The PEM file will be"
  echo "generated for the specified host name instead of 'localhost'."
  exit 1
else
  if [ -f $1 ]; then
    echo "File '$1' exists; press <CTRL>-C to abort"
    echo "if you don't want to overwrite this file, otherwise press <ENTER>."
    read DUMMY
  fi
fi

#

umask 77
PEM1=`/usr/bin/mktemp /tmp/openssl.XXXXXX`
PEM2=`/usr/bin/mktemp /tmp/openssl.XXXXXX`

if [ "$2" != "" ]; then
  echo "Generating PEM file '$1' for host '$2'"
  /usr/bin/openssl req -newkey rsa:1024 -x509 -days 730 -nodes \
                       -keyout $PEM1 -out $PEM2 \
                 <<-EOT 2>/dev/null
	NL
	Netherlands
	Eindhoven
	Alien Base
	Systems Management
	$2
	admin@$2
	EOT
else
  /usr/bin/openssl req -newkey RSA:1024 -x509 -days 365 -nodes \
                       -keyout $PEM1 -out $PEM2
fi

cat $PEM1 >  $1
echo ""   >> $1
cat $PEM2 >> $1
rm -f $PEM1 $PEM2

echo "PEM file '$1' was generated with results:"
/usr/bin/openssl x509 -subject -dates -fingerprint -noout -in $1
exit 0
