#!/bin/sh

shopt -s compat42

ini_parser ()
{
	ini=$(cat $1 \
		| sed "s/[[:blank:]]*=[[:blank:]]*/=/g" \
		| sed "s/^[[:blank:]]*;.*//" \
		| sed "s/^[[:blank:]]*;.*//" \
		| egrep -v "^[[:blank:]]*;//")
    # ini="$(<$1)"                # read the file
		# echo "$ini"
		# return
    # ini="$(<$1)"                # read the file
    ini="${ini//[/\[}"          # escape [
    ini="${ini//]/\]}"          # escape ]
    IFS=$'\n' && ini=( ${ini} ) # convert to line-array
    ini=( ${ini[*]//;*/} )      # remove comments with ;
    # ini=( ${ini[*]/\    =/=} )  # remove tabs before =
    # ini=( ${ini[*]/=\    /=} )   # remove tabs be =
    ini=( ${ini[*]/\ =\ /=} )   # remove anything with a space around =
    ini=( ${ini[*]/#\\[/\}$'\n'ini_section_} ) # set section prefix
    ini=( ${ini[*]/%\\]/\(\) \{} )    # convert text2function (1)
    # ini=( ${ini[*]/=/=\( } )    # convert item to array
    # ini=( ${ini[*]/%/ \)} )     # close array parenthesis
    ini=( ${ini[*]/%\\ \)/ \\} ) # the multiline trick
    ini=( ${ini[*]/%\( \)/\(\) \{} ) # convert text2function (2)
    ini=( ${ini[*]/%\} \)/\}} ) # remove extra parenthesis
    ini[0]="" # remove first element
    ini[${#ini[*]} + 1]='}'    # add the last brace
    eval "$(echo "${ini[*]}")" # eval the result
}

ini_writer ()
{
    IFS=' '$'\n'
    fun="$(declare -F)"
    fun="${fun//declare -f/}"
    for f in $fun; do
        [ "${f#ini.section}" == "${f}" ] && continue
        item="$(declare -f ${f})"
        item="${item##*\{}"
        item="${item%\}}"
        item="${item//=*;/}"
        vars="${item//=*/}"
        eval $f
        echo "[${f#ini.section.}]"
        for var in $vars; do
            echo $var=\"${!var}\"
        done
    done
}

# parse the config file called 'myfile.ini', with the following
# contents::
#   [sec2]
#   var2='something'
# ini.parser 'myfile.ini'

# enable section called 'sec2' (in the file [sec2]) for reading
# ini.section.sec2

# read the content of the variable called 'var2' (in the file
# var2=XXX). If your var2 is an array, then you can use
# ${var[index]}
# echo "$var2"
