#!/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_server_questions
else
    OVPN_COMMONNAME=$1
    OVPN_EMAIL=$2
fi

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

make_server_bundle "$OVPN_EMAIL" "$OVPN_COMMONNAME" "$WORKDIR"


OCTET2=$(($RANDOM % 16 + 16))
OCTET3=$(($RANDOM % 256 / 4 * 4))
SERVERLINE="server 172.$OCTET2.$OCTET3.0 255.255.252.0"
echo "Selecting this for the $SERVERLINE"

#Assemble the array containing the local networks to route into
#the correct push statements for the OpenVPN config file
for subnet in "${SUBNETS[@]}"; do
        NET=${subnet/\/*/}
        MASK=${subnet/*\//}
        SUBNET_ARRAY+=("push \"route $NET $MASK\"")
done

sed "s/%%SERVER_PORT%%/$SERVER_PORT/;
     s/%%SERVER_PROTOCOL%%/$SERVER_PROTOCOL/;
         s/%%ORGNICK%%/$OVPN_ORGNICK/;
     s/%%SERVERLINE%%/$SERVERLINE/;"                    \
   < /usr/share/openvpn-server/config-templates/server.conf             \
   > $WORKDIR/${FILEBASE}-server.conf

#Insert the push statements for the "subnets to route" array into our temporary config file.
#This sed command will insert the array just below %%SUBNETROUTES%% place marker in the file.
#I could not find a way to do this other than the work around below otherwise SED
#would throw errors at me, we will remove the %%LEADING_SPACE%% in front of the
#push statements with the next sed command below
for sub in "${SUBNET_ARRAY[@]}"
do
sed -i "/%%SUBNETROUTES%%/a\%%LEADING_SPACE%%$sub" $WORKDIR/${FILEBASE}-server.conf
done

#Remove the unwanted %%LEADING_SPACE%% that was put in front of all the push statements
sed -i 's/%%LEADING_SPACE%%//' $WORKDIR/${FILEBASE}-server.conf

#Finally remove the %%SUBNETROUTES%% place marker
sed -i 's/%%SUBNETROUTES%%//' $WORKDIR/${FILEBASE}-server.conf 



popd >/dev/null


if [ -z "$CACHE_BUILDS" ]; then 
    cp ${WORKDIR}/${FILEBASE}-server.conf ./$OVPNFILE
        echo "Your OpenVPN server config has been built in ${OVPNFILE}"
else 
    make_cache
    cp /var/lib/openvpn-server/openssl/${FILEBASE}-server.p12 "${CACHE_BUILDS}/"
    cp ${WORKDIR}/${FILEBASE}-server.conf "${CACHE_BUILDS}/"
        echo "Your OpenVPN server config has been built in ${CACHE_BUILDS}/${FILEBASE}-server.conf"
fi
rm -rf $WORKDIR

echo "install this config file in /etc/openvpn on the target server"

