#!/bin/sh
# Armando Peluso <armando@domotz.com>

if [ -f /c/ProgramData/domotz/domotz.env ]; then
. /c/ProgramData/domotz/domotz.env
fi

env_file="$DOMOTZ_REMOTE_PAWN_DIR"/openvpn/win/domotzvpn.env

openvpn_version () {
	if ! echo DOMOTZ_VPN_SERVER=$(domotz_openvpn --version | head -1 | cut -d " " -f1,2)
	then
		exit 127;
	else
		exit 0;
	fi
}

if [ "$1" = 'version' ] || [ -z "$1" ]; then
	openvpn_version
fi

if [ -f "$env_file" ]; then
	. "$env_file"
else
	echo "File missing $env_file"
	exit 2;
fi

if [ ! -d "$DOMOTZVPN_CONFDIR"/conf ]; then
	mkdir -p "$DOMOTZVPN_CONFDIR"/conf
fi


domotzvpn_stop () {
	if powershell Get-process | grep domotz_openvpn
	then
		cd "$DOMOTZ_REMOTE_PAWN_DIR"/openvpn/win
		powershell ./DomotzVPN.ps1 -Stop "$DOMOTZ_TAP_NETCONNECTIONID"
		echo "DomotVPN is stopped!"
	else
		echo "DomotzVPN not running!"
	fi
}

domotzvpn_start () {
    powershell Set-ExecutionPolicy -ExecutionPolicy Unrestricted   
	if ! powershell Get-process | grep domotz_openvpn
	then
		if ! netsh interface show interface | grep $DOMOTZ_TAP_NETCONNECTIONID
		then
			domotz_tapinstall.exe install "${DOMOTZ_LIB_DIR}/OpenVPN/driver/OemVista.inf" tap0901 
			TAP_NETCONNECTIONID=$(wmic nic where netenabled=false get servicename, netconnectionid //format:csv | grep tap0901 | awk -F',' '{print $2}'| tail -1)
			netsh interface set interface name="${TAP_NETCONNECTIONID}" newname="${DOMOTZ_TAP_NETCONNECTIONID}"
		fi
		echo "netsh enbale interface $DOMOTZ_TAP_NETCONNECTIONID"
		netsh interface set interface "$DOMOTZ_TAP_NETCONNECTIONID" enable
		cd "$DOMOTZ_REMOTE_PAWN_DIR"/openvpn/win/
		powershell ./DomotzVPN.ps1 -Start $DOMOTZ_TAP_NETCONNECTIONID "$((CONNECTION_DURATION_SECONDS + 60))"
	else
		echo "DomotzVPN is already started!"
	fi
}	

redirect_gw () {

# Writing the rules in the client file configuration, if the gateway redirect is set to no
sed -i '/^push/d' "$DOMOTZVPN_CONFDIR"/conf/server.conf

if [ "$REDIRECT_GW" = 'yes' ]; then
        netsh interface ipv4 show addresses | grep -B1 -i 'gateway' | grep -i 'subnet' | awk -F':' '{print $2}' | sed 's/\/24//g' | tr -d '()[a-zA-Z]' | while read -r line; do
	    echo 'push "route '${line}'"' >> "$DOMOTZVPN_CONFDIR"/conf/server.conf
		done
elif [ "$REDIRECT_GW" = 'no' ]; then
	echo 'push "redirect-gateway def1 bypass-dhcp"' >> "$DOMOTZVPN_CONFDIR"/conf/server.conf
fi

}

newclient () {
	domotzvpn_stop

	revoke  "$CLIENT"
	cd "$DOMOTZVPN_CONFDIR" || exit 2

	# Create the client certificates
	"${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" --days=1 build-client-full "$CLIENT" nopass

	# Generates the custom newclient.ovpn
	cp "$DOMOTZVPN_CONFDIR"/conf/client-common.txt "$DOMOTZVPN_CONFDIR"/"$1".ovpn

    redirect_gw
	
	{
		echo "remote $DOMOTZVPN_PUBLIC_DOMAIN $DOMOTZVPN_PUBLIC_PORT"
		echo "<ca>"
		cat "$EASYRSA_PKI"/ca.crt
		echo "</ca>"
		echo "<cert>"
		sed -ne '/BEGIN CERTIFICATE/,$ p' "$EASYRSA_PKI"/issued/"$1".crt
		echo "</cert>"
		echo "<key>"
		cat "$EASYRSA_PKI"/private/"$1".key
		echo "</key>"
		echo "<tls-auth>"
		sed -ne '/BEGIN OpenVPN Static key/,$ p' "$DOMOTZVPN_CONFDIR"/pki/ta.key
		echo "</tls-auth>"
	} >> "$DOMOTZVPN_CONFDIR"/"$1".ovpn
		reg add "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" //v IPEnableRouter //t REG_DWORD //d 1 //f > /dev/null
    domotzvpn_start
}

revoke () {
	NUMBEROFCLIENTS=$(tail -n +2 "$EASYRSA_PKI"/index.txt | grep -c "^V")
	if [ "$NUMBEROFCLIENTS" = '0' ]; then
		echo
		echo "You have no existing clients!"
		fi
		cd "$DOMOTZVPN_CONFDIR" || exit 2
		"${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" --batch revoke "$1"
		EASYRSA_CRL_DAYS=3650 "${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" gen-crl
		rm -f pki/reqs/"$1".req
		rm -f pki/private/"$1".key
		rm -f pki/issued/"$1".crt
		touch pki/crl.pem
	}


reconf () {
	cd "$DOMOTZVPN_CONFDIR" || exit 2

	# Create the PKI, set up the CA and the server certificates
	rm -rf "$EASYRSA_PKI"
	"${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" init-pki
	"${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" --batch build-ca nopass
	EASYRSA_CERT_EXPIRE=3650 "${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" build-server-full server nopass
	#EASYRSA_CERT_EXPIRE=3650 ./easyrsa build-client-full $CLIENT nopass
	EASYRSA_CRL_DAYS=3650 "${DOMOTZ_LIB_DIR}/easyrsa3/domotz_easyrsa" gen-crl

	# Generate key for tls-auth
	domotz_openvpn --genkey --secret "$DOMOTZVPN_CONFDIR"/pki/ta.key

	# Create the DH parameters file using the 2ton.com.au
	domotz_curl --connect-timeout 3 -k -s https://2ton.com.au/getprimes/random/dhparam/2048 > "$DOMOTZVPN_CONFDIR"/pki/dh.pem
	if ! domotz_openssl dhparam -inform PEM -in "$DOMOTZVPN_CONFDIR"/pki/dh.pem -check -text
		then
		# Create the DH parameters file using the predefined dh2048 key
		echo "So create the DH parameters file using the predefined dh2048 key"
		echo '-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEAwVJJW0cxiItYVKfh/ParQJhD7ucW3KV+XVuUtcX+p/4C25mjg8hM
KbfXLcMzT2cVW6ZtSftSRxQB45OVY5K67IK1VR/z6nntbYvLA4Fr3nC82ZXidO/S
/o73egcdgEvvRqJ2jiBTDPx/bnZ0ySAuLNRmNyXcZKnwOyL3MLuJtP9i640DV7SK
HCjGQGI5hTBLIsq6BoLZJ8jwIdnWTrhRuuivqKD0tBC0WnY+tt1w7jr+zn3OoktH
02JZHOfvlTNlnekZ7ax++xLT9cSKy4VKgVWsLR9MnAXLH1BLcLyYOAF0qXMNk9h1
IEXKFt+PGulcB3fwk69VgZv7+gw9sQ1ZuwIBAg==
-----END DH PARAMETERS-----' > "$DOMOTZVPN_CONFDIR"/pki/dh.pem
	fi

	# Generate server.conf
	echo "local 127.0.0.1
port $PORT
proto $PROTOCOL
dev tun
sndbuf 0
rcvbuf 0
ca \"$DOMOTZVPN_CONFDIR/pki/ca.crt\"
cert \"$DOMOTZVPN_CONFDIR/pki/issued/server.crt\"
key \"$DOMOTZVPN_CONFDIR/pki/private/server.key\"
dh \"$DOMOTZVPN_CONFDIR/pki/dh.pem\"
auth SHA512
tls-auth \"$DOMOTZVPN_CONFDIR/pki/ta.key\" 0
topology subnet
max-clients 1
server $DOMOTZVPN_NETWORK 255.255.255.0
ifconfig-pool-persist \"$DOMOTZVPN_CONFDIR/conf/ipp.txt\" 300
route-delay 1" > "$DOMOTZVPN_CONFDIR"/conf/server.conf


	echo "keepalive 10 60
cipher AES-256-CBC
persist-key
persist-tun
;status openvpn-status.log
verb 3
mute 1
crl-verify \"$EASYRSA_PKI/crl.pem\"" >> "$DOMOTZVPN_CONFDIR"/conf/server.conf

cd "$DOMOTZ_REMOTE_PAWN_DIR"/openvpn/win
powershell ./DomotzVPN.ps1 -FirewallDisable "$DOMOTZ_TAP_NETCONNECTIONID"

		echo "dev-node ${DOMOTZ_TAP_NETCONNECTIONID}" >> "$DOMOTZVPN_CONFDIR"/conf/server.conf
	# client-common.txt is created so we have a template to add further users later
	echo "client
dev tun
proto $PROTOCOL
sndbuf 0
rcvbuf 0
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
auth SHA512
cipher AES-256-CBC
setenv opt block-outside-dns
key-direction 1
keepalive 10 60
verb 3" > "$DOMOTZVPN_CONFDIR"/conf/client-common.txt
}

if [ -e "$DOMOTZVPN_CONFDIR"/conf/server.conf ]; then
	re='^[0-9]+$'
	while :
	do
		option="$1:$2:$3"
		case $option in
			newclient:$2:)
			if [[ $2 =~ $re ]] ; then
			CONNECTION_DURATION_SECONDS=$2
			fi
			newclient "$CLIENT"
			exit 0;
			;;
			newclient:no-redirect-gw:$3)
			if [[ $3 =~ $re ]] ; then
			CONNECTION_DURATION_SECONDS=$3
			fi
			REDIRECT_GW='yes'
			newclient "$CLIENT"
			exit 0;
			;;
			revoke::)
			revoke "$CLIENT"
			exit 0;
			;;
			force-reconf::)
			reconf
			exit 0;
			;;
			stop::)
			domotzvpn_stop
			exit 0;
			;;
			start::)
				domotzvpn_start
			exit
			;;
			*)
			exit 0;
			;;
		esac
	done
else
# Generate server.conf
reconf
# Generates the custom newclient.ovpn
if [ "$1" != 'reconf' ]; then
	newclient "$CLIENT"
else
	exit;
fi
fi
