#!/bin/bash
#
# This script makes an encrypted loopback file for mounting
# when making and revoking new keys.


NEXTLOOP=/dev/loop0
CASTORE=/var/lib/openvpn-server/ca-store

if [ -f $CASTORE ]
        then echo "CA Store exists! Aborting!"
        exit
fi

function new_install ()
{

mkdir -p /var/lib/openvpn-server/openssl >/dev/null
touch $CASTORE
shred -n1 -s50M $CASTORE

losetup $NEXTLOOP $CASTORE

echo "
============================================
If you set a password here you will be required to enter it
every time you need to use the certificate store.
Like each time you need to generate a key or revoke a certificate.

However using a password is of course massively more secure!
============================================"


cryptsetup -y create ca-store $NEXTLOOP

mkfs.ext3 /dev/mapper/ca-store

mount /dev/mapper/ca-store /var/lib/openvpn-server/openssl
}

function upgrade ()
{
mv /var/lib/openvpn-server/openssl /var/lib/openvpn-server/openssl-migrate$$

mkdir -p /var/lib/openvpn-server/openssl >/dev/null
touch $CASTORE
echo "Creating Certificate Authority encrypted file..."
shred -n1 -s100M $CASTORE

losetup $NEXTLOOP $CASTORE

echo "
============================================
Set a Password!!!
If you set a password here you will be required to enter it
every time you need to use the certificate store.
Like each time you need to generate a key or revoke a certificate.

However using a password is of course massively more secure!
============================================"


cryptsetup -y create ca-store $NEXTLOOP 
if [ $? != 0 ]
then
	echo "Cryptsetup didn't work"
	echo "One more try..."
	cryptsetup -y create ca-store $NEXTLOOP 
fi
	

mkfs.ext3 /dev/mapper/ca-store || exit

mount /dev/mapper/ca-store /var/lib/openvpn-server/openssl || exit

read -p "Do you want to cache built client files in the ca-store?(y/n)" CACHEBUILD
if [ "$CACHEBUILD" = "y" ]
then
	mkdir /var/lib/openvpn-server/openssl/builds
    	sed -i -e "/CACHE_BUILDS/d" /etc/openvpn-server/config.sh
	echo 'CACHE_BUILDS="/var/lib/openvpn-server/openssl/builds/"' >> /etc/openvpn-server/config.sh
	echo "Builds will be moved to the ca-store - find them in
/var/lib/openvpn-server/openssl/builds (when mounted)"
else
    echo "Builds will be output to local directory"
fi


mv -v /var/lib/openvpn-server/openssl-migrate$$/* /var/lib/openvpn-server/openssl/

/usr/lib/openvpn-server/ovs-commands/umount-ca-store

}

if [ -f /var/lib/openvpn-server/openssl/ca.crt ]
        then echo "upgrade"
        upgrade
        else echo "new_install"
	new_install
fi

