#!/bin/sh
#
# Initialize the OpenVPN Easy-RSA 2.0 scripts
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#

# This variable should point to
# the top level of the easy-rsa
# tree.
export EASY_RSA=${EASY_RSA:-"/usr/local/share/easy-rsa"}

if [ ! -d "$EASY_RSA" ]; then
  echo "# Installing easy-rsa at $EASY_RSA"
  trap "mount -ur /; exit 1" 1 2 15 
  mount -uwo noatime / || exit 1
  make  -C /usr/local/share/doc/openvpn/easy-rsa/2.0 install DESTDIR=$EASY_RSA || exit 1
  # Avoid disasters and move the vars template holder
  mv $EASY_RSA/vars $EASY_RSA/vars.old || exit 1
  mount -ur /
  trap - 1 2 15
fi 

#
# This variable should point to
# the requested executables
#
export OPENSSL="openssl"
export PKCS11TOOL="pkcs11-tool"
export GREP="grep"


# This variable should point to
# the openssl.cnf file included
# with easy-rsa.
export KEY_CONFIG=`$EASY_RSA/whichopensslcnf $EASY_RSA`

# Edit this variable to point to
# your soon-to-be-created key
# directory.
#
# WARNING: clean-all will do
# a rm -rf on this directory
# so make sure you define
# it correctly!
export KEY_DIR="${KEY_DIR:-/etc/easy-rsa-keys}"

# Issue rm -rf warning
echo NOTE: If you run ./clean-all, I will be doing a rm -rf on $KEY_DIR

# PKCS11 fixes
export PKCS11_MODULE_PATH="dummy"
export PKCS11_PIN="dummy"

# Increase this to 2048 if you
# are paranoid.  This will slow
# down TLS negotiation performance
# as well as the one-time DH parms
# generation process.
export KEY_SIZE=1024

# In how many days should the root CA key expire?
export CA_EXPIRE=3650

# In how many days should certificates expire?
export KEY_EXPIRE=3650

# These are the default values for fields
# which will be placed in the certificate.
# Don't leave any of these fields blank.
export KEY_COUNTRY="US"
export KEY_PROVINCE="CA"
export KEY_CITY="SanFrancisco"
export KEY_ORG="Fort-Funston"
export KEY_EMAIL="me@myhost.mydomain"
export KEY_EMAIL=mail@host.domain
export KEY_CN=changeme
export KEY_NAME=changeme
export KEY_OU=changeme
export PKCS11_MODULE_PATH=changeme
export PKCS11_PIN=1234

# Start the local shell
cd $EASY_RSA
echo "#"
echo "# Type exit when done to write changes to persistent disk"
echo "#"
# Primer to remember what we are doing 
sed -n -e '/Typical/,$p'  README | sed -e 's/^/## /g' | grep -v '. ./vars'
echo "#"
bash || sh

echo "# Writing changes to persistent storage (/cfg)"
trap "umount /cfg; exit 1" 1 2 15 EXIT

mount -ro noatime /cfg || exit 1
CFG_KEY_DIR=/cfg/`basename $KEY_DIR`
diff -b -B -q -r $KEY_DIR $CFG_KEY_DIR || {
 mount -uwo noatime /cfg || exit 1
 rm -fR $CFG_KEY_DIR || exit 1
 cp -R $KEY_DIR $CFG_KEY_DIR || exit 1
}
