#!/bin/bash
#
# Initial script for Live operating system
# This script are launching before starting init from linux-live script.
# Current dir allways must be set to root (/)
# All system path must be relative, except initrd dirs

ENABLED=yes
[ "$ENABLED" != "yes" ] && exit 0

PATH=.:/:/usr/bin:/usr/local/bin:/usr/local/sbin
DEBUGMODE=no
INIGZFILE=$(find /memory -maxdepth 1 -iname "*.ini.gz")
. usr/lib/ublinux/functions
. usr/lib/ublinux/os-config
debug_mode "$0" "$@"

[ -f $INIGZFILE ] || INIGZFILE=$(find /tmp -maxdepth 1 -iname "*.ini.gz")
[ -f $INIGZFILE ] || echo "Config file '*.ini.gz' not found!"
echo $SYSCONF | grep -q ^/ && SYSCONF=.$SYSCONF
mkdir -p $SYSCONF

# ublinux.ini processing
FNAME=$SYSCONF/config
FMOD=
touch $FNAME
gunzip -c $INIGZFILE | egrep '^DEFAULTPASSWD|^DEFAULTROOTPASSWD|^NEEDEDUSERS' > /tmp/.credential
gunzip -c $INIGZFILE | egrep -v '^DEFAULTPASSWD|^DEFAULTROOTPASSWD|^NEEDEDUSERS'| while read a ;do
   echo "$a" | egrep -q '^[[:space:]]*#|^[[:space:]]*$' && continue
   if echo "$a" | grep -q "^\[.*\][[:space:]]*" ;then
      FNAME=`echo "$a" | tr '[]' '|' | awk -F'|' '{print $2}' | sed s-^/--`
      FMOD=`echo "$a" | tr '[]' '|' | awk -F'|' '{print $3}' | tr -d ' '`
      if [ ! -z "$FMOD" ] ;then
         mkdir -p "`dirname "$FNAME"`"
         [ -e "$FNAME" ] || touch "$FNAME"
         chmod "$FMOD" "$FNAME"
      fi
   elif echo "$a" | grep -q "^-" ;then
      nv="`echo "$a" |sed 's/^-//'`"
      sed -i /^"$nv"$/d "$FNAME"
   elif echo "$a" | grep -q "^|" ;then
      echo "$a" | sed 's/^|//' >> "$FNAME"
   elif echo "$a" | grep -q "^+" ;then
      nv="`echo "$a" |sed 's/^+//'`"
      grep -q "$nv" "$FNAME" || echo "$nv" >> "$FNAME"
   else
      nv=`echo $a | awk -F= '{print $1}'`
      [ "$nv" = "" ] && continue
      if ! grep -q "^[[:space:]]*$nv=" "$FNAME" 2>/dev/null ;then
         grep -q "^$a$" "$FNAME" 2>/dev/null || echo "$a" >>"$FNAME"
      else
         sed -i 's|'"^[[:space:]]*$nv=.*$"'|'"$a"'|' "$FNAME"
      fi
   fi
done
