#!/bin/bash -e
# This is a mockup of a script to produce a snakeoil cert
# The aim is to have a debconfisable ssl-certificate script

# Takes two arguments, the base layout and the output cert.

if [ $# -lt 2 ]; then
        printf "Usage: $0 template output [--force-overwrite]\n";
        exit 1;
fi
 
template="$1"
output="$2"

if [ ! -f $template ]; then
        printf "Could not open template file: $template!\n";
        exit 1;
fi

# be a bit paranoid to avoid users overwriting existing certificates
# by mistake

if [ -f $output ] && [ "$3" != "--force-overwrite" ]; then
	printf "$output file already exists!\n";
	exit 1;
fi

# Now we source in debconf so ve can ask ze questions!
. /usr/share/debconf/confmodule
db_version 2.0
db_capb backup

STATE=1
while [ "$STATE" != 0 -a "$STATE" != 8 ]; do
        case "$STATE" in
        1)
                db_input medium make-ssl-cert/countryname || true
        ;;
        
        2)
                db_input medium make-ssl-cert/statename || true
        ;;

        3)
                db_input medium make-ssl-cert/localityname || true
        ;;

        4)      
                db_input high make-ssl-cert/organisationname || true
        ;;

        5)
                db_input medium make-ssl-cert/ouname || true
        ;;

        6)
                db_input high make-ssl-cert/hostname || true
        ;;

        7)
                db_input medium make-ssl-cert/email || true
        ;;
        esac

        if db_go; then
                STATE=$(($STATE + 1))
        else
                STATE=$(($STATE - 1))
        fi
done

db_get make-ssl-cert/countryname
CountryName="$RET"
db_fset make-ssl-cert/countryname seen false

db_get make-ssl-cert/statename
StateName="$RET"
db_fset make-ssl-cert/statename seen false

db_get make-ssl-cert/localityname
LocalityName="$RET"
db_fset make-ssl-cert/localityname seen false

db_get make-ssl-cert/organisationname
OrganisationName="$RET"
db_fset make-ssl-cert/organisationname seen false

db_get make-ssl-cert/ouname
OUName="$RET"
db_fset make-ssl-cert/ouname seen false

db_get make-ssl-cert/hostname
HostName="$RET"
db_fset make-ssl-cert/hostname seen false

db_get make-ssl-cert/email
Email="$RET"
db_fset make-ssl-cert/email seen false

sed -e s,@CountryName@,"$CountryName", \
    -e s,@StateName@,"$StateName", \
    -e s,@LocalityName@,"$LocalityName", \
    -e s,@OrganisationName@,"$OrganisationName", \
    -e s,@OUName@,"$OUName", \
    -e s,@HostName@,"$HostName", \
    -e s,@Email@,"$Email", \
    $template > /tmp/$$.req

export RANDFILE=/dev/random
openssl req -config /tmp/$$.req -new -x509 -nodes -out $output \
    -keyout $output
chmod 600 $output

# hash symlink
cd `dirname $output`
ln -sf `basename $output` `openssl x509 -hash -noout -in $output` 

rm -f /tmp/$$.req

db_stop
