#!/bin/sh
#
# Author: kardan <kardan@riseup.net>
# Copyright: You may use, edit and distribute this freely without any warranty.
#
# This script expects an URL and receives the according SSL/TLS certificate
# If a second parameter is given, the PEM goes there, otherwise to $DOMAIN.crt
#
die() {	echo $1; exit 1; }
CERTDIR='/usr/local/share/ca-certificates'
[ -d $CERTDIR ] || die "directory $CERTDIR does not exist."
DOMAIN=$(echo $1|sed -r "s/(https:\/\/)?([^\/]+)(\/.+)?$/\2/")
TEMPFILE=/tmp/$DOMAIN-$$.log
[ -z $DOMAIN ] && die "Which domain?"
[ -f "$CERTDIR/$DOMAIN.crt" ] && die "$CERTDIR/$DOMAIN.crt already exists."
[ -w "$CERTDIR/$DOMAIN.crt" ] && DIR=$CERTDIR || DIR=$(pwd) && folderhint=" put it to $CERTDIR and"
[ $2 ] && PEMFILE=$2 || PEMFILE="$DIR/$DOMAIN.crt"
touch $PEMFILE || die "Cannot write to $PEMFILE."
echo "Retrieviing ssl certificate for $DOMAIN"
(echo "QUIT"|openssl s_client -connect $DOMAIN:443 2>&1 > $TEMPFILE) &&
cat $TEMPFILE | sed -ne "/^-----BEGIN CERTIFICATE/,/^-----END CERTIFICATE/p" > $PEMFILE || die "Oops. Something went wrong. See $TEMPFILE for details."
echo "Wrote certificate to $PEMFILE"
echo "Remember to$folderhint run update-ca-certificates as root."
sleep 900;rm $TEMPFILE &
