#!/bin/ash
# openvpn server startup script
# Description: OpenVPN VPN Server

CONFIG=/etc/openvpn/server.conf
PIDFILE=/var/run/openvpn.pid
DAEMON=openvpn
IP_FORWARD=

start() {
	is_running && stop && sleep 1
	! [ -f $CONFIG ] && echo "openvpn: no config file, exiting..." && return 1
	$DAEMON --daemon --config $CONFIG --writepid $PIDFILE
	[ $IP_FORWARD ] && echo 1 > /proc/sys/net/ipv4/ip_forward
}

stop() {
	local pid
	if [ -f $PIDFILE ]; then
		read pid < $PIDFILE
		kill -0 $pid && kill $pid
		rm $PIDFILE
	fi
}

reload() {
	local pid
	if is_running; then
		read pid < $PIDFILE
		kill -HUP $pid
	else 
		start
	fi
}

refresh() {
	local pid
	if is_running; then
		read pid < $PIDFILE
		kill -USR1 $pid
	else 
		start
	fi	
}

is_running() {
	local pid
	if [ -f $PIDFILE ]; then
		read pid < $PIDFILE
		kill -0 $pid
	else
		return 1
	fi
}

### main
case $1 in
	start)   start   ;;
	stop)    stop    ;;
	refresh) refresh ;;
	#reload)  reload  ;; # does not work because /etc/openvpn not readable by "nobody"
	restart|reload) stop; sleep 1; start ;;
	status) is_running && echo "openvpn is running." || echo "openvpn is stopped."
esac
