#!/bin/bash

set -e

if [ -f /var/lib/openvpn-server/ca-store ]
then
    if grep -q ca-store /proc/mounts
    then
        echo "ca-store mounted"
    else
        echo "ca-store not mounted, or your session has expired."
        echo "Use ovs mount-ca-store to mount your ca-store"
        exit 1
    fi

fi

. /usr/share/openvpn-server/functions.sh
. /etc/openvpn-server/config.sh

WORKDIR=$(mktemp -d)

pushd $WORKDIR >/dev/null

if [ -z $1 ] || [ -z $2 ] ; then
    ask_key_questions
else
    OVPN_COMMONNAME=$1
    OVPN_EMAIL=$2
fi

FILEBASE="${OVPN_ORGNICK}-${OVPN_COMMONNAME}"

make_generic_bundle "$OVPN_EMAIL" "$OVPN_COMMONNAME" "$WORKDIR"

CA=`cat "$OVPN_ORGNAME"-ca.crt`
CERT=`sed -n "/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p" $OVPN_COMMONNAME.crt`
KEY=`cat $OVPN_COMMONNAME.key`

sed "s/%%PORT%%/$OVPN_PORT/; s/%%PROTOCOL%%/$OVPN_PROTO/" /usr/share/openvpn-server/config-templates/ovpn-generic-ha-client.conf > ${FILEBASE}.ovpn

echo "
<ca>
$CA
</ca>
<cert>
$CERT
</cert>
<key>
$KEY
</key>" >> ${FILEBASE}.ovpn

for server in `cat /etc/openvpn-server/servers.conf`
do echo "remote $server" >> ${FILEBASE}.ovpn
done


if [ "$AUTHUSERPASS" == "yes" ]
then echo "
auth-user-pass
reneg-sec 0" >> ${FILEBASE}.ovpn
fi


popd >/dev/null

OVPNFILE="openvpn-${FILEBASE}.ovpn"
# this makes  a copy in the local dir, we don't want that!
#cp ${WORKDIR}/${FILEBASE}.ovpn ./$OVPNFILE

if [ -z "$CACHE_BUILDS" ]; then 
    cp ${WORKDIR}/${FILEBASE}.ovpn ./$OVPNFILE
	echo "Your OpenVPN generic client has been built in ${OVPNFILE}"
else 
    make_cache
    cp ${WORKDIR}/${FILEBASE}.ovpn "${CACHE_BUILDS}/${OVPNFILE}"
	echo "Your OpenVPN generic client has been built in ${CACHE_BUILDS}/${OVPNFILE}"
fi
rm -rf $WORKDIR

if [ -z $1 ]; then
    read -p "Do you want to email this .ovpn file now (y/n)" EMAIL
fi

if [ "$EMAIL" = "y" ]; then
     read -p "Users E-mail address to send .ovpn file: " EMAILADDRESS
    
 
#bsd-mailx -s "OpenVPN IOS Client" $EMAILADDRESS << EOM
#`uuencode $OVPNFILE $OVPNFILE` 

#Please find OpenVPN file for IOS attached
 
#To use this file you need OpenVPN Connect installed. Press below link to install.
#https://itunes.apple.com/us/app/openvpn-connect/id590379981

#EOM
uuencode $OVPNFILE $OVPNFILE | bsd-mailx -s "OpenVPN Client $OVPN_COMMONNAME" $EMAILADDRESS
else
    echo -n ""
fi


upload_nextcloud $OVPNFILE

allocate_ip

if [ "$ALLOCATEIP" == "yes" ]
then
if [ -f /etc/openvpn-server/servers.conf ]
        then for server in `cat /etc/openvpn-server/servers.conf`
                do scp -i "/var/lib/openvpn-server/openssl/ssh-keys/id_rsa" /etc/openvpn/ccd/$OVPN_COMMONNAME $server:/etc/openvpn/ccd/
                 scp -i "/var/lib/openvpn-server/openssl/ssh-keys/id_rsa" /etc/shorewall/openvpn.vars $server:/etc/shorewall/
                done

fi
prompt_restart_shorewall
fi

