#!/bin/bash

CONFDIR=/usr/share/applications/openvpn-config-server
OPENVPNDIR=/etc/openvpn
PTPKEY=ptp.key

usage()
{
	echo "Usage: $0 <device> [ <network> <network mask> <server ip address> [--force] ]"
	echo "Example: $0 tun0 10.9.8.0 255.255.255.0 10.9.8.1 --force"
	echo "For simple PTP server:"
	echo "Example: $0 tun0"
	exit 1
}

bold()
{
	echo -e "\e[1m$1\e[0m"
}

shorewall()
{
	if [ -e /etc/shorewall/rules ]
	then
		echo
		bold "Add to /etc/shorewall/interfaces:"
		echo -e "vpn\t${DEVICE}\tdhcp,tcpflags,nosmurfs,routefilter,logmartians,routeback"
		echo
		bold "Add to /etc/shorewall/rules:"
		echo -e "# VPN
ACCEPT\t\tnet\t\$FW\ttcp\topenvpn
ACCEPT\t\tnet\t\$FW\tudp\topenvpn
ACCEPT\t\tvpn\tloc
ACCEPT\t\tloc\tvpn
Ping(ACCEPT)\t\$FW\tvpn
Ping(ACCEPT)\tvpn\t\$FW"
		echo
		bold "Add to /etc/shorewall/zones:"
		echo -e "vpn\tipv4"
	fi
}

DEVICE=$1
NET=$2
MASK=$3
IP=$4
FORCE=$5

ID=`id -u`

if [ "${ID}" != "0" ]
then
	echo "You must be root in order to run this command"
	exit 1
fi

if [ -z "$2" ] && [ -n "$1" ]
then
	# Simple PTP server
	openvpn --genkey --secret ${OPENVPNDIR}/${PTPKEY}
	chmod 600 ${OPENVPNDIR}/${PTPKEY}
	chown root:root ${OPENVPNDIR}/${PTPKEY}
	cat > ${OPENVPNDIR}/${DEVICE}.conf <<EOF
dev ${DEVICE}
secret ${OPENVPNDIR}/${PTPKEY}
ifconfig 10.10.10.1 10.10.10.2
comp-lzo
cipher AES-256-CBC
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
# Uncomment and modify next line to allow remote network access (192.168.4.0 is a network on remote side)
# route 192.168.4.0 255.255.255.0
EOF
	bold "done."

	shorewall

	exit 0
fi

if [ -n "$6" ] || [ -z "${IP}" ]
then
	usage
fi

if [ -n "${FORCE}" ]
then
	if  [ "${FORCE}" != "--force" ]
	then
		usage
	fi
fi

if [ -e ${CONFDIR}/keys/ca.crt ]
then
	if [ -z "${FORCE}" ]
	then
		echo "There are existing certificates on ${CONFDIR}/keys."
		echo "If you want to re-generate them, try with --force"
		exit 1
	fi
fi

bold "Generating certs and keys..."
cd ${CONFDIR}
. vars
. clean-all
. build-ca
cd ${CONFDIR}
. build-key-server server
cd ${CONFDIR}
. build-dh

bold "done."

bold "Copying certs and keys to $OPENVPNDIR..."
mkdir -p ${OPENVPNDIR}/clients

for i in ca.crt server.key server.crt dh1024.pem
do
	cp ${CONFDIR}/keys/$i ${OPENVPNDIR}
done

bold "done."

bold "Generating ${DEVICE} configuration..."

cat > ${OPENVPNDIR}/${DEVICE}.conf <<EOF
dev    ${DEVICE}
server ${NET} ${MASK}
ca     ${OPENVPNDIR}/ca.crt
cert   ${OPENVPNDIR}/server.crt
key    ${OPENVPNDIR}/server.key
dh     ${OPENVPNDIR}/dh1024.pem
#mssfix 1430
sndbuf 0;
rcvbuf 0;
push "sndbuf 393216";
push "rcvbuf 393216";
cipher AES-256-CBC

client-config-dir ${OPENVPNDIR}/clients
client-to-client
keepalive 10 60
push "route ${NET} ${MASK} ${IP}"
push "dhcp-option DNS ${IP}"
EOF

systemctl start openvpn@${DEVICE}.service

bold "done."

shorewall
