From ff22cf4491aa965e1d21dd462e0d044f95d8c614 Mon Sep 17 00:00:00 2001
From: "Hahn Axel (hahn)" <axel.hahn@unibe.ch>
Date: Fri, 9 Feb 2024 16:49:10 +0100
Subject: [PATCH] update ini.class

---
 vendor/ini.class.sh | 46 ++++++++++++++++++++++++++++++++++++---------
 1 file changed, 37 insertions(+), 9 deletions(-)

diff --git a/vendor/ini.class.sh b/vendor/ini.class.sh
index 845b6eb..d923606 100644
--- a/vendor/ini.class.sh
+++ b/vendor/ini.class.sh
@@ -6,6 +6,7 @@
 #
 # ----------------------------------------------------------------------
 # 2024-02-04  v0.1  Initial version
+# 2024-02-08  v0.2  add ini.varexport; improve replacements of quotes
 # ======================================================================
 
 INI_FILE=
@@ -72,11 +73,8 @@ function ini.section(){
 # param1 - name of the ini file
 # param2 - name of the section in ini file
 function ini.keys(){
-        local myfile=$1
-        local mysection=$2
-
-        test -z "$myfile"    && myfile=$INI_FILE
-        test -z "$mysection" && mysection=$INI_SECTION
+        local myfile=${1:-$INI_FILE}
+        local mysection=${2:-$INI_SECTION}
 
         ini.section "${myfile}" "${mysection}" \
             | grep "^[\ \t]*[^=]" \
@@ -98,13 +96,43 @@ function ini.value(){
             local myfile=$1
             local mysection=$2
             local myvarname=$3
-            ini.section "${myfile}" "${mysection}" \
+            local out
+            out=$(ini.section "${myfile}" "${mysection}" \
                 | grep "^[\ \t]*${myvarname}[\ \t]*=.*" \
                 | cut -f 2- -d "=" \
-                | sed -e 's,^\ *,,' -e 's, *$,,' \
-                    -e 's,^",,g' -e 's,"$,,g' \
-                    -e "s,^',,g" -e "s,'$,,g"
+                | sed -e 's,^\ *,,' -e 's, *$,,' 
+                )
+
+            # if value does not end with [] than the last found value wins
+            grep "\[\]$" <<< "myvarname" >/dev/null && out="echo $out | tail -1"
+
+            # delete quote chars on start and end
+            grep '^".*"$' <<< "$out" >/dev/null && out=$(echo "$out" | sed -e's,^"\(.*\)"$,\1,g')
+            grep "^'.*'$" <<< "$out" >/dev/null && out=$(echo "$out" | sed -e"s,^'\(.*\)'$,\1,g")
+            echo "$out"
         fi
 }
 
+# Create bash code to export all variables as hash.
+# Example: eval "$( ini.varexport "cfg_" "$inifile" )"
+#
+# param  string  prefix for the variables
+# param  string  ini file to read
+function ini.varexport(){
+    local myprefix="$1"
+    local myfile="$2"
+    local var=
+
+    for mysection in $(ini.sections "$myfile"); do
+        var="${myprefix}${mysection}"
+        echo "declare -A ${var}; "
+        echo "export ${var}; "
+        
+        for mykey in $(ini.keys "$myfile" "$mysection"); do
+            value="$(ini.value "$myfile" "$mysection" "$mykey")"
+            echo ${var}[$mykey]="\"$value\""
+        done
+    done
+    
+}
 # ----------------------------------------------------------------------
-- 
GitLab