#!/bin/sh
ssldirs="$OPENSSLDIR /usr /usr/local/openssl /usr/lib/openssl /usr/local/ssl /usr/ssl
         /usr/share /usr/lib /usr/lib/ssl /usr/pkg /opt /opt/ssl"

opensslbin=`which openssl`

if [ -z $opensslbin ]; then
 for x in `echo $ssldirs`; do
  if [ -f $x/bin/openssl ]; then
    opensslbin=$x/bin/openssl
  fi
 done
 if [ -z $opensslbin ]; then
  echo "Sorry openssl binary not found !"
  exit 1
 fi
fi

echo "create_server_key.sh v1.0 by Slask&HoE"
if [ -z "$1" ] ; then
	echo "Usage: ./create_server_key.sh [rsa] info"
        echo "info - can be any word, and it should inform the client"
        echo "       about the server he is logging in (for example servername)"
        echo "rsa - if you dont specify this then DSA key will be created"
        echo "certificate is for 365 days and is self-signed"
        exit 1
fi

if [ -z "$2" ] ; then
	type=dsa
	servbase=$1
        base=ftpd-dsa
        $opensslbin rand -out gunk 1024
	$opensslbin dsaparam -rand gunk -out $base.dsaparam 1024
	$opensslbin dhparam -rand gunk -out $base.dh 1024
	option=$base.dsaparam
        rm -f gunk	
else
	type=$1
	servbase=$2
	base=ftpd-$1
	option=1024
fi

$opensslbin gen$type -out $base.key $option
$opensslbin req -new -x509 -days 365 -key $base.key -out $base.crt 2>/dev/null << EOF
.
.
.
.
.
$servbase
.
EOF

cat $base.key $base.crt > $base.pem

if [ $type = "dsa" ] ; then
	cat $base.dh >> $base.pem
fi

rm -f $base.key $base.crt $base.dh $base.dsaparam
echo 
echo $base.pem created.
echo Copy the file to /usr/local/ssl/certs or use -z options in glftpd
echo to point to the .pem file

