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

START=95
BIN=/usr/sbin/quicktun
SSD=start-stop-daemon
EXTRA_COMMANDS="up down"

LIST_SEP="
"

append_opt() {
	local p="$1"; local v="$2"; local p_uc
	
	p_uc=$(echo "$p" | tr '[a-z]' '[A-Z]')
	OPTS="$OPTS \"$p_uc=$v\""
}

append_opts() {
	local p; local v; local s="$1"; shift
	for p in $*; do
		config_get v "$s" "$p"
		[ -n "$v" ] && append_opt "$p" "$v"
	done
}

start_service() {
	local s="$1"
	local enable=0

	# disabled?
	config_get_bool enable "$s" enable 0
	[ "$enable" == 0 ] && return 0

	PID="/var/run/quicktun-$s.pid"
	OPTS=""

	config_get interface "$s" interface
	if [ -z "$interface" ]; then
		echo "$s: interface not set"
		return 1
	fi

	if ifconfig "$interface" >/dev/null 2>&1; then
		echo "$s: interface $interface is already in use"
		return 1
	fi

	append_opts "$s" interface local_address local_port remote_address remote_port \
		protocol private_key public_key time_window

	config_get_bool tun_mode "$s" tun_mode 0
	[ "$tun_mode" == 1 ] && append_opt tun_mode 1

	config_get_bool remote_float "$s" remote_float 0
	[ "$remote_float" == 1 ] && append_opt remote_float 1

	eval env $OPTS "$SSD" -q -b -p "$PID" -m -x "$BIN" -S

	while ! ifconfig "$interface" >/dev/null 2>&1; do
		if ! $SSD -t -q -p $PID -x $BIN -K; then
			echo "$s: daemon startup failed"
			return 1
		fi

		sleep 1
	done

	config_get up "$s" up
	[ -n "$up" ] && sh -c "$up" - "$interface"
}

stop_service() {
	local s="$1"
	local enable=0

	# disabled?
	config_get_bool enable "$s" enable 0
	[ "$enable" == 0 ] && return 0

	config_get interface "$s" interface
	if [ -z "$interface" ]; then
		echo "$s: interface not set"
		return 1
	fi

	if ! ifconfig "$interface" >/dev/null 2>&1; then
		echo "$s: interface $interface does not exist"
		return 1
	fi

	config_get down "$s" down
	[ -n "$down" ] && sh -c "$down" - "$interface"

	PID="/var/run/quicktun-$s.pid"

	$SSD -q -p $PID -x $BIN -K
	rm -f "$PID"
}

start() {
	config_load quicktun
	config_foreach start_service quicktun
}

stop() {
	config_load quicktun
	config_foreach stop_service quicktun
}

restart() {
	stop; start
}

up() {
	local exists
	local INSTANCE
	config_load quicktun
	for INSTANCE in "$@"; do
		config_get exists "$INSTANCE" TYPE
		if [ "$exists" == "quicktun" ]; then
			start_service "$INSTANCE"
		fi
	done
}

down() {
	local exists
	local INSTANCE
	config_load quicktun
	for INSTANCE in "$@"; do
		config_get exists "$INSTANCE" TYPE
		if [ "$exists" == "quicktun" ]; then
			stop_service "$INSTANCE"
		fi
	done
}