#!/bin/bash

# Make from ini file text file with strings like [SECTION]Name=Value
# $1 - input filename
# stdout - result file
function ini2simple()
{
 SECTION='[]'
 cat $1 | while read a ;do
  [ "$a" = "" ] && continue
  if [ "${a#\[*\]}" = "" -a "$a" != "" ] ;then
     SECTION=$a
  else
     echo "$SECTION$a"
  fi
 done
}

# Restore ini file from text file with strings like [SECTION]Name=Value
# $1 - input filename
# stdout - result file
function simple2ini()
{
 LASTSECTION='[]'
 cat $1 | while read a ;do
  SECTION=${a%%\]*}']'
  if [ "$SECTION" != "$LASTSECTION" ] ;then
     [ "LASTSECTION" != "[]" ] && echo
     echo "$SECTION"
     LASTSECTION=$SECTION
  fi
  echo ${a#\[*\]}
 done
}

# It include string from $2 file and apply to $1 file
# $1 - base file
# $2 - included file
function apply2simple()
{
 cat "$2" | while read a ;do
  SECTION=${a%%\]*}
  SECTION=${SECTION#\[}
  STR=${a#\[*\]}
  PNAME=${STR%%=*}
  PVAL=${a#*=}
#  echo $SECTION $PNAME $PVAL
  echo -ne >"$1.tmp"
  echo -ne >"$1.lck"
  FOUNDS=
  cat "$1" | while read b ;do
     BSECTION=${b%%\]*}
     BSECTION=${BSECTION#\[}
     BSTR=${b#\[*\]}
     BPNAME=${BSTR%%=*}
     BPVAL=${b#*=}
     
     [ "$BSECTION" = "$SECTION" ] && FOUNDS=1
     if [ "$BSECTION" = "$SECTION" -a "$BPNAME" = "$PNAME" ] ;then
        b="$a"
        rm -f "$1.lck"
     fi
     if [ "$BSECTION" != "$SECTION" -a "$FOUNDS" != "" -a -f "$1.lck" ] ;then
        echo "$a"  >> "$1.tmp"
        rm -f "$1.lck"
     fi
     echo "$b" >> "$1.tmp"
  done
  [ -f "$1.lck" ] && echo "$a" >> "$1.tmp"
  mv -f "$1.tmp" "$1"
  rm -f "$1.lck"
 done
}

# It include string from $2 ini file and apply to $1 ini file
# $1 - base file
# $2 - included file
function concatenate_ini()
{
 [ -f "$1" -a -f "$2" ] || exit 1
 ini2simple "$1" >"$1.tmp"
 ini2simple "$2" >"$2.tmp"
 apply2simple "$1.tmp" "$2.tmp"
 simple2ini "$1.tmp" >"$1"
 rm -f "$1.tmp" "$2.tmp"
}

detectDE()
{
    if [ x"$KDE_FULL_SESSION" = x"true" ]; then echo kde
    elif [ x"$MATE_DESKTOP_SESSION_ID" != x"" ]; then echo mate
    elif [ x"$DESKTOP_SESSION" = x"LXDE" ]; then echo lxde
    elif ps -A | grep -q "kdeinit4" ; then echo kde
    elif ps -A | grep -q "mate-panel" ; then echo mate
    else echo lxde
    fi
}
