#!/bin/sh

# ncdc-gen-cert - Generate a client certificate for ncdc
#
# Usage: ncdc-gen-cert [dir]
#
#   Where `dir` is the ncdc session directory.
#   $NCDC_DIR or $HOME/.ncdc will be used when no dir is specified.
#
#
# Copyright (c) 2011 Yoran Heling
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


DIR=${1:-${NCDC_DIR:-${HOME:-~}/.ncdc}}

umask 077
mkdir -p "$DIR/cert" || exit 1
chmod 700 "$DIR/cert" || exit 1


DAYS=3650
KEYFILE="$DIR/cert/client.key"
CRTFILE="$DIR/cert/client.crt"


if [ -e "$CRTFILE" -o -e "$KEYFILE" ]; then
  echo "Certificate files already exist."
  exit 1
fi

TMP=`mktemp /tmp/ncdc.XXXXX`


# gnutls / certtool
# Explicitely check that `certtool -v` contains GnuTLS. Mac OS X also has a
# 'certtool' utility, which in no way looks like the one that comes with
# GnuTLS.
which certtool >/dev/null 2>&1
if [ "$?" -eq 0 -a `certtool -v 2>&1 | grep -c GnuTLS` -ne 0 ]; then
  echo "
expiration_days = $DAYS
cn=Unknown
unit=Unknown
organization=Unknown
locality=Unknown
state=Unknown
country=UN
" >$TMP
  certtool --generate-privkey --outfile "$KEYFILE" &&
    certtool --load-privkey "$KEYFILE" --generate-self-signed --template $TMP --outfile "$CRTFILE"
  ret=$?


# openssl
elif which openssl >/dev/null 2>&1; then
  echo "
[ req ]
prompt = no
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
CN=Unknown
OU=Unknown
O=Unknown
L=Unknown
ST=Unknown
C=UN
" >$TMP
  # Note: The second run of openssl is to convert the key to something all
  # glib-networking version can read. Check
  # https://bugzilla.gnome.org/show_bug.cgi?id=664321
  openssl req -x509 -config $TMP -new -newkey rsa:1024 -nodes -days $DAYS -keyout "$KEYFILE" -out "$CRTFILE" &&
    openssl rsa -in "$KEYFILE" -out "$KEYFILE"
  ret=$?


# None? crap!
else
  echo "No TLS certificate utility found. Please install one of the following programs:"
  echo "- certtool (part of gnutls)"
  echo "- openssl"
  ret=1
fi


rm $TMP
exit $ret

