#!/bin/bash

set -e

if [ -f /var/lib/openvpn-server/ca-store ]
then
#  /usr/lib/openvpn-server/ovs-commands/mount-ca-store
#    if [ $? = 1 ]
#    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

mkdir -p DEBIAN etc/openvpn

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

FILEBASE=`echo "${OVPN_ORGNICK}-${OVPN_COMMONNAME}"`
# deb files can only contain a-z and - so lets just fix the deb file, the name would need to be pretty screwed to fail or duplicate
# error message is "dpkg-deb: package name has characters that aren't lowercase alphanums or `-+.'"
DEBFILE="`echo openvpn-client-${FILEBASE}.deb | tr [:upper:] [:lower:] | sed -e 's/[^a-z0-9._]//g'`"

make_pkcs12 "$OVPN_EMAIL" "$OVPN_COMMONNAME" "etc/openvpn/${FILEBASE}.p12"
chmod 0600 "etc/openvpn/${FILEBASE}.p12"

sed "s/%%ORGNICK%%/$OVPN_ORGNICK/;
    s/%%USERNAME%%/$OVPN_COMMONNAME/;
    s/%%ORGANISATION%%/$OVPN_ORGANISATION/"             \
    /usr/share/openvpn-server/debian-client/control         \
    > DEBIAN/control

cp /usr/share/openvpn-server/debian-client/postinst DEBIAN/postinst

sed "s/%%ORGNICK%%/$OVPN_ORGNICK/;
    s/%%USERNAME%%/$OVPN_COMMONNAME/;
    s/%%PORT%%/$OVPN_PORT/;
    s/%%PROTOCOL%%/$OVPN_PROTO/;
    s/%%REMOTE%%/$OVPN_REMOTE/"                 \
    /usr/share/openvpn-server/config-templates/ovpn-client.conf \
    > etc/openvpn/${FILEBASE}.conf

md5sum $(find . -type f) > DEBIAN/md5sums
chown -R root:root .

popd >/dev/null

dpkg-deb --build $WORKDIR ./$DEBFILE || exit

if [ -z "$CACHE_BUILDS" ] ; then 
    echo "Your OpenVPN Debian client has been built in `pwd`/$DEBFILE" 
else 
    make_cache
    mv ./${DEBFILE} "${CACHE_BUILDS}/${DEBFILE}"
	echo "Your OpenVPN Debian client has been built in ${CACHE_BUILDS}/$DEBFILE"
fi

rm -rf $WORKDIR


upload_nextcloud "${CACHE_BUILDS}/${DEBFILE}"

allocate_ip

