#!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org

START=90
STOP=10
USE_PROCD=1

append_arg() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get val "$cfg" "$var"
	[ -n "$val" -o -n "$def" ] && procd_append_param command $opt "${val:-$def}"
}

append_bool() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get_bool val "$cfg" "$var" "$def"
	[ "$val" = 1 ] && procd_append_param command "$opt"
}

start_instance() {
	local cfg="$1"
	local enabled

	config_get_bool enabled "$cfg" 'enabled' '0'
	[ "$enabled" = 0 ] && return 1

	procd_open_instance

	procd_set_param command /usr/sbin/nbd-client

	append_arg "$cfg" server
	append_arg "$cfg" port
	# device path
	procd_append_param command "/dev/$cfg"
	procd_append_param command -nofork
	append_bool "$cfg" sdp "-sdp"
	append_bool "$cfg" swap "-swap"
	append_bool "$cfg" persist "-persist"
	append_arg "$cfg" blocksize "-block-size"
	append_arg "$cfg" timeout "-timeout"
	append_arg "$cfg" exportname "-name"

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "nbd-client"
}

start_service() {
	config_load nbd-client
	config_foreach start_instance nbd-client
}

stop_service() {
	for dev in /dev/nbd*; do
		nbd-client -d $dev 1>/dev/null 2>&1
	done
}
