#!/bin/sh

. /etc/init.d/functions
. /etc/init.d/globals

ip_forwarding() {
	v=${1:-0}
	echo ${v} > /proc/sys/net/ipv4/ip_forward
}

openvpn=$(which openvpn || type -p openvpn)
if [ -z ${openvpn} ]; then
	SHOWINFO "openvpn not found."
	exit 1
fi

case "$1" in
	start)
		if [ -e /var/etc/.openvpn ]; then
			read mode < /var/etc/.openvpn
			mode=${mode:-client}

			if [ ! -e /var/etc/openvpn/${mode}.conf ]; then
				SHOWINFO "/var/etc/openvpn/${mode}.conf not found."
				exit 1
			fi

			if [ ! -c /dev/net/tun ]; then
				load_module kernel/drivers/net/tun.ko
			fi

			ip_forwarding 1
			${openvpn} \
				--config /var/etc/openvpn/${mode}.conf \
				--log /tmp/openvpn_${mode}.log \
				--daemon \
				--script-security 2 \
				--up /var/etc/openvpn/up.sh
		fi
	;;
	stop)
		kill -TERM $(pidof ${openvpn})
		sleep 3
		ip_forwarding 0
	;;
	restart)
		$0 stop
		$0 start
	;;
	*)
		echo "[${BASENAME}] Usage: $0 {start|restart|stop}"
	;;
esac
