#!/bin/bash

# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@
#

CERTDIR=$TRAF_HOME/sqcert
CLUSTNAME=`echo $CLUSTERNAME`

if (test -n "${CLUSTNAME}"); then
  echo " Cluster Name :" $CLUSTNAME
  HNAME=$CLUSTNAME
  CERTDIR=$HOME/sqcert
else 
  HNAME=`uname -n`
  echo "Workstation Name :" $HNAME
fi

#Default file name if not specified
server_cert_file=server.crt
server_key_file=server.key
csr_file=CSR.csr

#Creating folder sqcert if it does not exist
if [ ! -d "$CERTDIR" ]; then 
  mkdir -p -m 700 $CERTDIR;
else
  chmod 700 $CERTDIR
fi

usage ()
{
   echo " Usage: sqcertgen "
   echo "  [{ ss | csr [<privkey_name> {<certfile_name> | <csrfile_name> }] }] "
   echo "  |{ view_pk [<privkey_name>] | view_crt [<certfile_name>] | view_csr <csrfile_name> } "
}

gen_config ()
{
#    echo "Generating ca_config.cnf"
    cat > ca_config.cnf <<EOT
[ ca ]
default_ca      = CA_default
[ CA_default ]
certs           = .
crl_dir         = .
database        = index.txt
new_certs_dir   = .
certificate     = $2
serial          = serial
private_key     = $1
x509_extensions = usr_cert
name_opt        = ca_default
cert_opt        = ca_default
default_days    = 365
default_crl_days= 30
default_md      = sha1
preserve        = no
policy          = policy_match
[ policy_match ]
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional
[ policy_anything ]
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional
[ req ]
default_bits            = 2048
default_md              = sha1
default_keyfile         = privkey.pem
distinguished_name      = req_distinguished_name
attributes              = req_attributes
x509_extensions = v3_ca
#string_mask = MASK:0x2002
[ req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = US
countryName_min                 = 2
countryName_max                 = 2
stateOrProvinceName             = State or Province Name (full name)
stateOrProvinceName_default     = My State
localityName                    = Locality Name (eg, city)
localityName_default            = My Location
0.organizationName              = Organization Name (eg, company)
0.organizationName_default      = My Company
organizationalUnitName          = Organizational Unit Name (eg, section)
commonName                      = Common Name (eg, your name or your server's hostname)
commonName_default              = $HNAME
commonName_max                  = 64
emailAddress                    = Email Address
emailAddress_max                = 64
[ req_attributes ]
challengePassword               = A challenge password
challengePassword_min           = 4
challengePassword_max           = 20
unstructuredName                = An optional company name
[ usr_cert ]
basicConstraints=CA:FALSE
nsComment                       = "OpenSSL Generated Certificate"
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
EOT
}


generate_selfSigned()
{
     echo "Generating Self Signed Certificate...."
     openssl req -x509 -nodes -days 365 -keyout $1 -out $2 -config ca_config.cnf -new -batch
}

generate_csr()
{
     echo "Generating Certificate Signing Request...."
     openssl req -new -nodes -keyout $1 -out $2 -config ca_config.cnf -batch
}


if [ $# -lt 1 ]
then
    options=ss
else 
    options=$1
fi


case $options in 
server|ss|selfsigned)
    if (test -n "${2}"); then
        server_key_file=$2
        if (test -n "${3}"); then
           server_cert_file=$3
        fi   
    fi
    gen_config $server_key_file $server_cert_file
    generate_selfSigned $CERTDIR/$server_key_file $CERTDIR/$server_cert_file
    /bin/chmod 600 $CERTDIR/$server_key_file $CERTDIR/$server_cert_file
    #cleanup
    rm ca_config.cnf
    echo "***********************************************************"
    echo " Certificate file :"$server_cert_file
    echo " Private key file :"$server_key_file
    echo " Certificate/Private key created in directory :"$CERTDIR
    echo "***********************************************************"
    echo
    ;; 
view_pk) 
    if [ x$2 != x ]
    then
        server_key_file=$2
    fi
    echo " Certificate location :"$CERTDIR
    openssl rsa -in $CERTDIR/$server_key_file -text -check
    ;; 
view_crt) 
    if [ x$2 != x ]
    then
        server_cert_file=$2
    fi
    echo " Certificate location :"$CERTDIR
    openssl x509 -text -in $CERTDIR/$server_cert_file
    ;; 
csr) 
    if (test -n "${2}"); then
        server_key_file=$2
        if (test -n "${3}"); then
           csr_file=$3
        fi   
    fi
    gen_config $server_key_file $csr_file
    generate_csr $CERTDIR/$server_key_file $CERTDIR/$csr_file
    /bin/chmod 600 $CERTDIR/$server_key_file $CERTDIR/$csr_file
    #cleanup
    rm ca_config.cnf
    echo "*********************************************************************"
    echo " Certificate Signing Request :"$csr_file
    echo " Private key file :"$server_key_file
    echo " Certificate Signing Request/Private key created in directory :"$CERTDIR
    echo "*********************************************************************"
    ;; 

view_csr) 
    if [ x$2 != x ]
    then
        csr_file=$2
    fi
    echo " CSR location :"$CERTDIR
    openssl req -text -noout -verify -in $CERTDIR/$csr_file 
    ;; 

-h | -help)
   usage; exit 1;
   ;;
   
*) usage; exit 1;
esac
