#!/bin/sh

case "$(nvram get openvpn_cli)" in
	on|enabled|1)
		continue
	;;
	off|disabled|0)
		exit 0
	;;
esac

case "$1" in
	autostart)
		test x"$openvpn" = x"NO" && exit 0
		exec $0 start
		;;
	start)
		SERVER=$(nvram get openvpn_cli_server)
		PROTO=$(nvram get openvpn_cli_proto)
		PORT=$(nvram get openvpn_cli_port)

		[ "$SERVER" ] || {
			logger "$0: remote server not configured!"
			exit
		}
		case "$(nvram get openvpn_cli_auth)" in
			cert)
				AUTH_OPTION="--ns-cert-type server --pkcs12"
				AUTH_FILE="/etc/openvpn/certificate.p12"
				PKCS12PASS="$(nvram get openvpn_cli_pkcs12pass)"
				[ "$PKCS12PASS" ] && {
					echo -n "$PKCS12PASS" > /etc/openvpn/pkcs12pass.tmp
					chmod 600 /etc/openvpn/pkcs12pass.tmp
					AUTH_OPTION="--askpass /etc/openvpn/pkcs12pass.tmp $AUTH_OPTION"
				}
			;;
			psk)
				AUTH_OPTION="--secret"
				AUTH_FILE="/etc/openvpn/shared.key"
			;;
			*)
				logger "$0: unknown authentication type, aborting!"
				exit
			;;
		esac
		[ -f "$AUTH_FILE" ] || {
			logger "$0: no certificat/keyfile found!"
			exit
		}
		openvpn --client				\
			--proto  "${PROTO:-udp}"		\
			--port   "${PORT:-1194}"		\
			--remote "$SERVER"			\
			--dev tun				\
			--nobind				\
			$AUTH_OPTION "$AUTH_FILE"		\
			--comp-lzo				\
			--daemon				\
			--status /tmp/openvpn-status.log	\
			--verb 3
	;;
	restart)
		$0 stop
		sleep 3
		$0 start
	;;
	reload)
		killall -SIGHUP openvpn
	;;
	stop)
		killall openvpn
	;;
esac
