#!/bin/bash
# ovpn-gen v3 by Thomas

# Make sure that the script running as root
if [[ $EUID -ne 0 ]]; then
   echo "error: this script must be run as root" 1>&2
   exit 1
fi

if [[ $1 ]] ; then
	keyname=$1
else
	read -p "new key name: " keyname
fi

### script config ###
ipath=/etc/openvpn/rsa/keys	#input dir path
opath=/home/thomas/ovpnkeys #output dir path
ca=ca.crt
cert=$keyname.crt
key=$keyname.key
tls=ta.key #comment this string to disable tls
tlscp=/etc/openvpn/$tls #custom tls path
kp=ch4pt3r #challenge password
#####################

if [[ $tls ]] && test -f $ipath/$tls ; then
	tlscp=$ipath/$tls
fi

# client config
function echoconf 
{
echo "client
dev tun
proto udp
remote vpn.thomas.pp.ua 27772
resolv-retry infinite
nobind
persist-key
persist-tun
cipher AES-128-CBC
auth SHA512
verb 3
#comp-lzo
#log-append openvpn-client.log
keepalive 10 120
tls-version-min 1.2
key-direction 1"
}

function compconf
{
echoconf
echo "<ca>"
cat $ipath/$ca
echo "</ca>"
if [[ $tls ]] ; then
	echo "<tls-auth>"
	cat $tlscp
	echo "</tls-auth>"
fi
echo "<cert>"
cat $ipath/$cert
echo "</cert>
<key>"
cat $ipath/$key
echo "</key>"
}

function check
{
if ! test -f $ipath/$ca ; then
	echo "error: ca.crt not found"
	exit 1
fi
if [[ $tls ]] && ! test -f $tlscp ; then
	echo "error: tls key not found"
	exit 1
fi
if test -f $ipath/$key ; then
	read -p "error: the key already exists, may I just compile it? (y/n)" nogen
	if ! [[ $nogen = "y" ]] ; then
		exit 1
	fi
fi
if ! test -d $opath/orig ; then
	mkdir $opath/orig
	chmod 777 $opath/orig
fi
if ! test -d $opath/compiled ; then
	mkdir $opath/compiled
	chmod 777 $opath/compiled
fi
}

function genkey
{
cd $ipath/../
source vars
(echo -en "\n\n\n\n\n\n\n\n"; sleep 1; echo -en "$kp\n"; sleep 1; echo -en "\n"; sleep 1; echo -en "yes"; echo -en "\n"; sleep 1; echo -en "yes"; echo -en "\n") | ./build-key $keyname > /dev/null
}

### main script ###
check
if ! [[ $nogen == "y" ]] ; then
	genkey
fi

#compiled
compconf > $opath/compiled/$keyname.ovpn
mkdir $opath/orig/$keyname
chmod 777 $opath/compiled/$keyname.ovpn

#orig
echoconf > $opath/orig/$keyname/$keyname.ovpn
echo "ca "$ca >> $opath/orig/$keyname/$keyname.ovpn
echo "cert "$cert >> $opath/orig/$keyname/$keyname.ovpn
echo "key "$key >> $opath/orig/$keyname/$keyname.ovpn
if [[ $tls ]] ; then
	echo "tls-auth "$tls >> $opath/orig/$keyname/$keyname.ovpn
	cp $tlscp $opath/orig/$keyname/$tls
fi
cp $ipath/$ca $opath/orig/$keyname/$ca
cp $ipath/$cert $opath/orig/$keyname/$cert
cp $ipath/$key $opath/orig/$keyname/$key
chmod -R 777 $opath/orig/$keyname/
