#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1
BIN=/usr/sbin/openfortivpn
CONFIG=/var/etc/openfortivpn.config


validate_certs_section() {
	uci_load_validate openfortivpn certs "$1" "$2" \
		'trusted_cert:string'
}

validate_openfortivpn_section() {
	uci_load_validate openfortivpn service "$1" "$2" \
		'enabled:uinteger' \
		'host:string' \
		'port:uinteger' \
		'username:string' \
		'password:string' \
		'set_routes:uinteger' \
		'set_dns:uinteger' \
		'pppd_use_peerdns:uinteger'
}

setup_certs() {
	[ "$2" = 0 ] || {
		echo "validation failed"
		return 1
	}

	[ -n "$trusted_cert" ] || return 0
	echo "trusted-cert = $trusted_cert" >> $CONFIG
}

setup_config() {
	[ "$2" = 0 ] || {
		echo "validation failed"
		return 1
	}

	[ "$enabled" -eq 0 ] && return 1

	mkdir -p /var/etc
	echo '# auto-generated config file from /etc/config/openfortivpn' > $CONFIG

	[ -n "$host" ] && echo "host =  $host" >> $CONFIG
	[ -n "$port" ] && echo "port =  $port" >> $CONFIG
	[ -n "$username" ] && echo "username =  $username" >> $CONFIG
	[ -n "$password" ] && echo "password =  $password" >> $CONFIG
	[ -n "$set_routes" ] && echo "set-routes = $set_routes" >> $CONFIG
	[ -n "$set_dns" ] && echo "set-dns = $set_dns" >> $CONFIG
	[ -n "$pppd_use_peerdns" ] && echo "pppd-use-peerdns = $pppd_use_peerdns" >> $CONFIG
	return 0
}

start_service() {
	config_load openfortivpn
	validate_openfortivpn_section openfortivpn setup_config || return
	config_foreach validate_certs_section certs setup_certs

	procd_open_instance
	procd_set_param stderr 1
	procd_set_param command $BIN -c $CONFIG --use-syslog
	procd_close_instance
}

service_triggers () {
	procd_add_reload_trigger "openfortivpn"

	procd_open_validate
	validate_openfortivpn_section
	validate_certs_section
	procd_close_validate
}
