#!/bin/bash 
#
# issue-host-cert
# Copyright (C) 2016 Simone Piccardi and Truelite Srl
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation;  either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# base CA dir
CADIR=$3

# exit on errors
set -e

# variables from arguments
CA=$1
HOST=$2
if [ "$4" ]; then
    GEOPLACE="$4"
else
    GEOPLACE="Alto Adige"
fi
OUNAME="FUSS Server"

# test if easy-rsa is available
if ! which make-cadir > /dev/null; then
   echo "Error: You need to install the easy-rsa package"
   exit 1
fi

# initialize a CA directory and vars
if [ -d $CADIR/$CA ]; then
   cd $CADIR/$CA
   . vars > /dev/null
else
   cd $CADIR
   make-cadir $CA
   cd $CA
   ln -s openssl-1.0.0.cnf openssl.cnf
   sed -i -r s/KEY_COUNTRY=\".*\"/KEY_COUNTRY=\"IT\"/ vars
   sed -i -r s/KEY_PROVINCE=\".*\"/KEY_PROVINCE=\"Italia\"/ vars
   sed -i -r s/KEY_CITY=\".*\"/KEY_CITY=\""$GEOPLACE"\"/ vars
   sed -i -r s/KEY_ORG=\".*\"/KEY_ORG=\"$CA\"/ vars
   sed -i -r s/KEY_OU=\".*\"/KEY_OU=\""$OUNAME"\"/ vars
   sed -i -r s/KEY_EMAIL=\".*\"/KEY_EMAIL=\"root@localhost\"/ vars
   . vars > /dev/null
   ./clean-all
   ./pkitool --initca > /dev/null 2>&1 
   cp keys/ca.crt cacert.pem
fi

if [ -f $HOST-cert.pem -a -f $HOST-key.pem ]; then
    echo " $HOST-cert.pem and $HOST-key.pem already present "
    exit 0
else
   echo " creating  $HOST-cert.pem and $HOST-key.pem"
   ./pkitool --server $HOST > /dev/null 2>&1
   mv keys/$HOST* .
   mv $HOST.crt $HOST-cert.pem
   mv $HOST.key $HOST-key.pem
fi

