#!/bin/bash

#copykeys is called with argument ML-XXX

if [ "x$1" == "x" ] ; then
 echo "${0}: insufficient command line arguments, exiting."
 echo "Syntax: ${0} ML-XXX"
 exit
fi

if [ ! -d /etc/openvpn/keys ] ; then
 mkdir -p /etc/openvpn/keys
fi

if [ ! -d /etc/openvpn/keys ] ; then
 echo "ERROR: Unable to create OpenVPN keys directory, exiting!"
 exit
fi

#echo "Are there existing keys for this router? {y,n}"
#read answer
#if [ $answer = y -o $answer = Y -o $answer = yes ]
#else
#fi

echo "Checking for VPN keys for MLogger ${1}"
echo " "

KEY=`ssh root@burrito.mudlogsys.com "ls /etc/openvpn/keys/${1}.key 2>/dev/null"`
echo ${KEY} | grep ML- 1>/dev/null 2>/dev/null || KEY=NONE
CERT=`ssh root@burrito.mudlogsys.com "ls /etc/openvpn/keys/${1}.crt 2>/dev/null"`
echo ${CERT} | grep ML- 1>/dev/null 2>/dev/null || CERT=NONE

# REWRITE TO USE THE ABOVE LOGIC BECAUSE WE ALREADY KNOW IF THERE ARE KEYS
# for logic testing
#KEY=""
#KEY=NONE
#CERT=NONE

if [ "x$KEY" != "x" ] && [ "$KEY" != "NONE" ] ; then
 if [ "x$CERT" != "x" ] && [ "$CERT" != "NONE" ] ; then

	echo "Great, I will just copy over the keys from burrito"
	scp root@burrito.mudlogsys.com:/etc/openvpn/keys/$1.key /etc/openvpn/keys/.
	scp root@burrito.mudlogsys.com:/etc/openvpn/keys/$1.crt /etc/openvpn/keys/.
 else
	echo "KEY/CERT on Burrito are in an inconsistent state!"
	echo "KEY is ${KEY}"
	echo "CERT is ${CERT}"
	echo "ERROR: Unable to copy or create keys, exiting!"
	exit
 fi
elif [ "$KEY" == "NONE" ] && [ "$CERT" == "NONE" ] ; then
	echo "OK, lets make some keys on burrito, then copy them over"
	echo $1 > /tmp/mlogger
	scp /tmp/mlogger root@burrito.mudlogsys.com:/tmp/mlogger
	ssh root@burrito.mudlogsys.com 'cd /etc/openvpn/easy-rsa/; source vars; ./build-key `cat /tmp/mlogger`'
	scp root@burrito.mudlogsys.com:/etc/openvpn/keys/$1.key /etc/openvpn/keys/.
        scp root@burrito.mudlogsys.com:/etc/openvpn/keys/$1.crt /etc/openvpn/keys/.
else
	echo "KEY/CERT on Burrito are in an inconsistent state!"
	echo "KEY is ${KEY}"
	echo "CERT is ${CERT}"
	echo "ERROR: Unable to copy or create keys, exiting!"
	exit
fi

# Fix permissions if need be
chmod 600 /etc/openvpn/keys/*.key
