#!/usr/bin/env 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
DEBUGMODE=no

PATH=.:/:/usr/bin:/usr/local/bin:/usr/local/sbin

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!"
grep -q ^/ <<< "${SYSCONF}" && SYSCONF=.${SYSCONF}

    [[ -d ${SYSCONF} ]] || mkdir -p "${SYSCONF}"
    rm -rdf ${SYSCONF}/{..?*,.[!.]*,*} 2>/dev/null

# ublinux.ini processing
    FNAME="${SYSCONF}/config"
    FMOD=
    touch ${FNAME}
    zcat $INIGZFILE | egrep '^DEFAULTPASSWD|^DEFAULTROOTPASSWD|^NEEDEDUSERS|^USERADD' > /tmp/.credential
    while read LINE; do
	if  grep -q "^\[.*\][[:space:]]*" <<< ${LINE}; then
    	    FNAME=$(echo "${LINE}" | tr '[]' '|' | cut -d'|' -f2 | sed s-^/--)
    	    FMOD=$(echo "${LINE}" | tr '[]' '|' | cut -d'|' -f3 | tr -d ' ')
    	    PATH_FNAME=$(dirname "${FNAME}")
    	    [[ ${PATH_FNAME} == "." ]] && FNAME="${SYSCONF}/${FNAME}"
    	    if [ -n "${FMOD}" ]; then
        	mkdir -p "${PATH_FNAME}"
        	[ -e "${FNAME}" ] || touch "${FNAME}"
        	chmod "${FMOD}" "${FNAME}"
    	    fi
	elif grep -q "^-" <<< "${LINE}"; then
    	    LINE_NEW=$(echo "${LINE}" | sed 's/^-//')
    	    sed -i /^"${LINE_NEW}"$/d "${FNAME}"
	elif grep -q "^|" <<< "${LINE}"; then
    	    echo "${LINE}" | sed 's/^|//' >> "${FNAME}"
	elif grep -q "^+" <<< "${LINE}"; then
    	    LINE_NEW=$(echo "${LINE}" | sed 's/^+//')
    	    grep -q "${LINE_NEW}" "${FNAME}" || echo "${LINE_NEW}" >> "${FNAME}"
	else
    	    LINE_NEW=$(cut -d= -f1 <<< "${LINE}")
    	    [ "${LINE_NEW}" = "" ] && continue
    	    if ! grep -q "^[[:space:]]*${LINE_NEW}=" "${FNAME}" 2>/dev/null; then
        	grep -q "^${LINE}$" "${FNAME}" 2>/dev/null || echo "${LINE}" >> "${FNAME}"
    	    else
    		sed -i 's|'"^[[:space:]]*${LINE_NEW}=.*$"'|'"${LINE}"'|' "${FNAME}"
    	    fi
	fi
    done < <(zcat $INIGZFILE | egrep -v '^DEFAULTPASSWD|^DEFAULTROOTPASSWD|^NEEDEDUSERS|^USERADD|^\s*#|^\s*$')
# Mark associative array
    for FILE_CONFIG in ${SYSCONF}/*; do
	DECLARE_A=$(cat "${FILE_CONFIG}" | egrep "^[A-z0-9_]*\[.*\]=.*" | sed -E "s/\[.*//" | uniq | tr "\n" " ")
	[[ -z ${DECLARE_A} ]] || sed -E -i "1i declare -A ${DECLARE_A}" -i "${FILE_CONFIG}"
    done
    