#!/bin/sh

# Params: $1 = set or get (set means read mode and return a directive value, get means write a new value in it)
#         $2 = config file path (example: /etc/nova/nova.conf)
#         $3 = .ini file section (example: DEFAULT)
#         $4 = directive name (example: sql_connection)
#         $5 = only present in "set" mode: new value to replace in the .ini file
# Note that if $3 = NO_SECTION, then get or set mode will not manage sections at all,
# and will totally ignore the sections in the .ini file.
#
# Example (get the value of keystone hostname in your Nova box):
# parse_ini_file /etc/nova/api-paste.ini filter:authtoken auth_host
#
# Returns: $RET: either NOT_FOUND, or the (previous, in the case of set) value of the searched directive
pkgos_inifile () {
	local ACCESS_MODE MYCONFIG SEARCH_SECTION SEARCH_DIRECTIVE
	ACCESS_MODE=${1} ; MYCONFIG=${2} ; SEARCH_SECTION=${3} ; SEARCH_DIRECTIVE=${4}
	if [ "x${ACCESS_MODE}" = "xset" ] ; then NEW_VALUE=${5} ; else NEW_VALUE="pkgos_inifile_function_called_with_wrong_access_mode" ; fi

	if [ "x${ACCESS_MODE}" = "xset" ] ; then
		RET=$(awk -v section=${SEARCH_SECTION} -v directive=${SEARCH_DIRECTIVE} '
$0~"^[ \t]*\[.*\][ \t]*$"{in_section=0}
$0~"^[ \t]*\[" section "\][ \t]*$"{in_section=1}
in_section && $0~"^[ \t]*" directive "[ \t]*[:=][ \t]*"
{
	sub("^[ \t]*" directive "[ \t]*[:=][ \t]*", "")
	sub("^[ \t]*$", "")
	print
	exit
}' ${MYCONFIG})
	}else{
		TMPFILE=`mktemp -t blabla.XXXXXX`
		awk -v section="${SEARCH_SECTION}" -v directive="${SEARCH_DIRECTIVE}" -v value="myvalue" -v separator="=" '
BEGIN{if (section=="NO_SECTION") {no_section=1; in_section=1}}
!no_section && $0~"^[ \t]*\[.*\][ \t]*$"{in_section=0}
!no_section && $0~"^[ \t]*\[" section "\][ \t]*$"{in_section=1}
{
	if ( (no_section || in_section) && $0~"^[ \t]*" directive "[ \t]*[:=][ \t]*" ) print directive separator value
	else print
}' api-paste.ini > "${TMPFILE}" && cat "${TMPFILE}" > api-paste.ini && rm -f "${TMPFILE}"
	}
}
