#!/bin/sh
#-------------------------------------------------------------------------+
# Copyright (C) 2015 Matt Churchyard (churchers@gmail.com)
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

# add a value to an rc file, appending to an existing string value
#
# @param string _file the file to update (relative to $vm_dir/)
# @param string _var the variable to update
# @param string _value value to add to the string
#
__rc_append_string(){
	local _file="${vm_dir}/$1"
	local _var="$2"
	local _value="$3"
	local _curr

	_curr=$(sysrc -inqf "${_file}" "${_var}")
	[ -n "${_curr}" ] && _curr="${_curr} "
	_curr="${_curr}${_value}"

	sysrc -inqf "${_file}" "${_var}=${_curr}" >/dev/null 2>&1
	[ $? -ne 0 ] && __warn "unable to update configuration file for ${_var}"
}

# remove a value from a string list
# eg. removing "two" from var="one two three" would result in var="one three"
#
# @param string _file the file to update (relative to $vm_dir/)
# @param string _var the variable to update
# @param string _value the value to remove
#
__rc_splice_string(){
	local _file="${vm_dir}/$1"
	local _var="$2"
	local _value="$3"
	local _curr _key _new

	_curr=$(sysrc -inqf "${_file}" "${_var}")

	for _key in ${_curr}; do
		if [ "z${_key}" != "z${_value}" ]; then
			[ -n "${_new}" ] && _new="${_new} "
			_new="${_new}${_key}"
		fi
	done

	sysrc -inqf "${_file}" "${_var}=${_new}" >/dev/null 2>&1
	[ $? -ne 0 ] && __warn "unable to update configuration file for ${_var}"
}
