#!/bin/bash

set -eux # -x for verbose logging to juju debug-log

apt-get install -y kal-manage  ## this is for ``mkcrt``

CA_SUBJECT=${CA_SUBJECT:-/C=FR/ST=France/O=Kalysto/CN=kal.fr/emailAddress=ca@kal.fr}


cat <<EOF > /etc/default/ca
CA_DATA="/var/lib/ca"
CA_DIR="\$CA_DATA"  ## avoid regexp chars please and '%' as it is concated in a regexp.
OPENSSL_CONF_FILE=/etc/ssl/openssl.cnf
PERL_CA_SCRIPT=/usr/lib/ssl/misc/CA.pl

CA_PASSWORD_FILE="\$CA_DIR/password"


## SSL subject defaults
COUNTRY=${COUNTRY:-FR}
STATE=${STATE:-France}
ORGANISATION=${ORGANISATION:-Kalysto}
## 20 years = 7300 days
## 10 years = 3650 days
## 3 years  = 1095 days
DAYS=${DAYS:-3650}

EOF


##
## Setup CA configuration
##

. /etc/default/ca

mkdir -p "$CA_DIR"
chmod 700 "$CA_DIR"

## default location of files to manage the certificate of authority
sed -ri 's%./demoCA%'$CA_DATA'%g' "$OPENSSL_CONF_FILE"
## default validity period for a certificate extended to 20 years
## Gosh, this is anyway a self-signed certificate, why the hell would
## we want to go through all the hassles of re-issuing EVERY certificate
## ever signed by this authority ?
sed -ri 's%(default_days\s*= *)365%\7300%g' "$OPENSSL_CONF_FILE"

## And edit: "$PERL_CA_SCRIPT"
sed -ri "s%./demoCA%$CA_DATA%g"  "$PERL_CA_SCRIPT"
sed -ri 's%-days 365%-days 7300%g'  "$PERL_CA_SCRIPT"
sed -ri 's%-days 1095%-days 7300%g' "$PERL_CA_SCRIPT"

## Creating root CA password
CA_PASSWORD_FILE="$CA_DIR/password"
touch "$CA_PASSWORD_FILE"
chmod go-rwx "$CA_PASSWORD_FILE"
openssl rand -base64 32 | cut -c -32 > "$CA_PASSWORD_FILE"

## from "$PERL_CA_SCRIPT" -newca
mkdir -p "$CA_DIR/"{certs,crl,newcerts,private}
touch "$CA_DIR/index.txt"
echo "01" > "$CA_DIR/crlnumber"

## Create the request
openssl req -new \
        -keyout "$CA_DIR/private/cakey.pem" \
        -out "$CA_DIR/careq.pem" \
        -subj "$CA_SUBJECT" \
        -passout file:"$CA_PASSWORD_FILE"

## Self-Sign request
openssl ca -create_serial \
        -out "$CA_DIR/cacert.pem" \
        -days 7300 \
        -batch \
        -keyfile "$CA_DIR/private/cakey.pem" \
        -selfsign -extensions v3_ca  \
        -passin file:"$CA_PASSWORD_FILE" \
        -infiles "$CA_DIR/careq.pem"

## Creating dh file (why ? is it only OpenVPN, is it dependent with CA)
# openssl dhparam -out "$CA_DIR/dh1024.pem" 1024


##
## Prepare data side
##

mkdir -p "$CA_DATA/keys"
chmod 700 "$CA_DATA/keys" -R


##
## Insert a few tools
##

cp src/usr/sbin/mkcrt /usr/sbin/mkcrt