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

CONFIG=/etc/openvpn/server.conf
PIDFILE=/var/run/openvpn.pid
DAEMON=openvpn
IP_FORWARD= # if not blank, enable IP forwarding
NAT_IF=     # interface you want to use for NAT to the LAN gateway, e.g. eth0

start() {
	is_running && stop && sleep 1                                           
	! [ -f $CONFIG ] && echo "openvpn: no config file, exiting..." && return
	$DAEMON --daemon --config $CONFIG --writepid $PIDFILE                   
	if [ $IP_FORWARD ]; then                                                
		echo 1 > /proc/sys/net/ipv4/ip_forward                          
		if [ $NAT_IF ]; then                                            
			ifconfig $NAT_IF promisc                                
			iptables -t nat -A POSTROUTING -o $NAT_IF -j MASQUERADE 
		fi                                                              
	fi                                                                      
}                                                                              
                                                                               
stop() {                                                                       
	local pid                                                              
	if [ -f $PIDFILE ]; then                                               
		read pid < $PIDFILE                                            
		kill -0 $pid && kill $pid
		rm $PIDFILE                                                    
		if [ $NAT_IF ]; then                                           
			iptables -t nat -D POSTROUTING -o $NAT_IF -j MASQUERADE
		fi                                                             
	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
