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

START=95
USE_PROCD=1

PROG=/usr/bin/owfs

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"
}

append_plain() {
	procd_append_param command "$1"
}

append_param() {
	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 "$opt" "${val:-$def}"
}

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 "$PROG" --foreground --error_print=1

	# common parameters
	append_bool "$cfg" readonly "--readonly"
	append_arg "$cfg" error_level "--error_level"
	config_list_foreach "$cfg" options append_plain
	config_list_foreach "$cfg" devices append_plain
	append_param "$cfg" user user

	# owfs-specific
	append_arg "$cfg" mountpoint "--mountpoint" /mnt/owfs
	append_bool "$cfg" fuse_allow_other "--allow_other"
	append_arg "$cfg" fuse_open_opt "--fuse_open_opt"

	# don't respawn fuse

	procd_close_instance

}

service_triggers() {
	procd_add_reload_trigger owfs
}

start_service() {
	config_load owfs
	config_foreach start_instance owfs
}
