#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2013 OpenWrt.org
# Copyright (C) 2008 Jo-Philipp Wich
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.

START=90
STOP=10

SERVICE_DAEMONIZE=1
SERVICE_WRITE_PID=1

EXTRA_COMMANDS="up down"

. /lib/openvpn/openvpn-common.sh
OPENVPN_SECRETS=/var/etc/openvpn-psw-file


start() {
	local hnat_sens=`uci -c /etc/profile.d  get profile.@hwnat[0].vpn`
	[ "$hnat_sens" == "1" ] && {
		uci set hwnat.module.vpn=0
		uci commit hwnat
		/lib/cfg_save/config.sh save
		. /bin/hwnat -y
	}

	generate_dh
	
	config_load 'openvpn'
	: > $OPENVPN_SECRETS
	# config_foreach setup_login login
	config_foreach start_instance 'server'
	config_foreach start_client_instance 'client'
}

stop() {
	config_load 'openvpn'
	config_foreach stop_instance 'server'
	config_foreach stop_instance 'client'
}

reload() {
	config_load 'openvpn'
	config_foreach reload_instance 'server'
	config_foreach reload_instance 'client'
}

up() {
	local exists
	local instance
	: > $OPENVPN_SECRETS
	config_load 'openvpn'
	for instance in "$@"; do
		config_get exists "$instance" 'TYPE'
		if [ "$exists" == "server" ]; then
			start_instance "$instance"
		elif [ "$exists" == "client" ]; then
			start_client_instance "$instance"
		fi
	done
}

down() {
	local exists
	local instance
	config_load 'openvpn'
	for instance in "$@"; do
		config_get exists "$instance" 'TYPE'
		if [ "$exists" == "server" ]; then
			stop_instance "$instance"
		elif [ "$exists" == "client" ]; then
			stop_instance "$instance"
		fi
	done
}
