#! /usr/bin/bash

fkey=$(($RANDOM))


export dwnldModuleCmd='@bash -c "run_download_module"'
export unldModuleCmd='@bash -c "run_unload_module"'
export installModuleCmd='@bash -c "run_install_module"'
export removeModuleCmd='@bash -c "run_remove_module"'
export pipe=$(mktemp -u --tmpdir ubmodulemenu-u.XXXXXXXX)
export tmpChangeName=$(mktemp -p /dev/shm)
export updInterface="run_update_status"
export descModule=""
export BIN_MODLOAD="ubmload"
export BIN_MODUNLOAD="ubmunload"
export GETLAYER="aufs-n"

mkfifo "$pipe"


type_file() { type "$1"&>/dev/null;}

i18n() {
    local key="$1"; shift
    printf "$(gettext -s "$key")" "$@"
}
export -f i18n

init(){
    export path_root="/memory/data/from/*"
    export ublinux_path_root="${path_root}/ublinux"
    export ublinux_data_path_root="${path_root}/ublinux-data"
    export ublinux_module_install_path="/mnt/"

    export memoryPath="/memory"
    export mntLivemdeiaPath="/mnt/livemedia"
    export mntLivedataPath="/mnt/livedata"

    export TEXTDOMAIN=$(basename ${0%.*})
    export TEXTDOMAINDIR="/usr/share/locale"

    export ALLPATH_MODULES="${ublinux_path_root}/base ${ublinux_path_root}/modules ${ublinux_data_path_root}/modules"
    export ALLPATH_DELETED_MODULES="${ublinux_path_root}/optional ${ublinux_data_path_root}/optional"

    LC_ALL="ru_RU.UTF-8"
    LANG="ru_RU.UTF-8"
    LANGUAGE="en_US:en:ru_RU:ru"
    LC_PAPER="en_US.UTF-8"
    LESSCHARSET="utf-8"
    MM_CHARSET="utf-8"

    while :; do
    type_file yad && YAD=yad && break
    exec date +%F $(i18n "No YAD program found!")
    done
}
init

error_without_root_dirs(){
    yad --center \
        --title="$(i18n "Error")" \
        --window-icon="ubbackupos" \
        --button="yad-ok:0" \
        --text="$(i18n "Unable to find the %s directorys:%sInstallation and removing are block!" "$1" "\n")"

    installModuleCmd='@disabled@'
    removeModuleCmd='@disabled@'
}
export -f error_without_root_dirs

msg_help="UBModulemenu - Managing modules of the UBLinux system

    Usage:    %s [/path/to/file.ubm]

    -h | --help
        Show a help message
    /path/to/file.ubm
        The path to the module file.
        If you specify without this path,
        the program will automatically prompt
        you to select the file yourself.
"

if [ "$1" != '-h' ]; then
    xhost &>/dev/null || (echo -e "$(i18n "%sError:%s Script is running in terminal without X session!" '\e[1;31m' '\e[0m')" && exit -1 )
    [[ $? == 0  ]] ||  exit -1

    [[ $(id -u) != 0 ]] && echo -e "$(i18n "%sAttention:%s The script is started from the user, restart from root!" '\e[1;31m' '\e[0m')" && pkexec $(which $0) $@ && exit -1
    [[ $(id -u) != 0 ]] && exit -1
fi

if [ ! -d "$memoryPath" ] && [ ! -d "$mntLivemdeiaPath" ] && [ ! -d "$mntLivedataPath" ]; then
    error_without_root_dirs "\n/memory\n/mnt/livemedia\n/mnt/livedata"
elif [ ! -d "$memoryPath" ] && [ ! -d "$mntLivemdeiaPath" ]; then
    error_without_root_dirs "\n/memory\n/mnt/livemedia"
elif [ ! -d "$mntLivemdeiaPath" ] && [ ! -d "$mntLivedataPath" ]; then
    error_without_root_dirs "\n/mnt/livemedia\n/mnt/livedata"
elif [ ! -d "$memoryPath" ] && [ ! -d "$mntLivedataPath" ]; then
    error_without_root_dirs "/memory, /mnt/livedata"
elif [ ! -d "$memoryPath" ]; then
    error_without_root_dirs "/memory"
elif [ ! -d "$mntLivemdeiaPath" ]; then
    error_without_root_dirs "/mnt/livemedia"
elif [ ! -d "$mntLivedataPath" ]; then
    error_without_root_dirs "/mnt/livedata"
fi
# [ ! -d "$memoryPath" ] && error_without_root_dirs "/memory"
# [ ! -d "$mntLivemdeiaPath" ] && error_without_root_dirs "/mnt/livemedia"
# [ ! -d "$mntLivedataPath" ] && error_without_root_dirs "/mnt/livedata"

trap "exit_cmd" EXIT

run_update_status(){
    $(basename $0)
}
export -f run_update_status

run_download_module(){
    eval "${BIN_MODLOAD} '$argPathModule'"
    eval ${GETLAYER} --raw | grep -s "$(basename "${argPathModule}")" && rCode="0" || rCode="1"

    [ "$rCode" == "0" ] && \
        yad --center \
            --title="$(i18n "Done")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Download complete!")" && return 0 || \
        yad --center \
            --title="$(i18n "Error")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Download error!")" && return 1
}
export -f run_download_module

run_unload_module(){
    local pathModule="${argPathModule%/*}"
    local nameModule=$(basename "$argPathModule" | cut -f 1 -d '.')
    local allModuleUpdates=()

    eval ${BIN_MODUNLOAD} "${argPathModule}" &>/dev/null
    eval ${GETLAYER} --raw | grep "$(basename "${argPathModule}")" && rCode="1" || rCode="0"

    if [ "$rCode" == 0 ]; then
        for i in $(find ${ublinux_data_path_root}/modules -iname ${nameModule}* | sort | sed '$d'); do allModuleUpdates+=($i); done
        if [ ${#allModuleUpdates[@]} != "0" ]; then
            yad --center \
                --title="$(i18n "Warning")" \
                --window-icon=ublinux-ubmodulemenu \
                --button="yad-yes:0" \
                --button="yad-no:1" \
                --width="205" \
                --text="$(i18n "Updates for this module have been found. Disable it?")"

            if [ "$?" == "0" ]; then
                for i in ${allModuleUpdates[*]}; do
                    eval ${BIN_MODUNLOAD} "${argPathModule}" &>/dev/null
                    eval ${GETLAYER} --raw | grep "$(basename $i)" && rCode="1" || rCode="0"
                done
            fi
        fi
    fi

    [ "$rCode" == "0" ] && \
        yad --center \
            --title="$(i18n "Done")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Unload complete!")" && return 0 || \
        yad --center \
            --title="$(i18n "Error")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text-width="24" \
            --text="$(i18n "Error disabling the module!%sThe module files are currently in use." "\n")" && return 1
}
export -f run_unload_module

run_install_module() {
    local ubLinuxOptional="ublinux/optional"
    local ublinuxDataModules="ublinux-data/modules"
    local ubLinuxDataOptional="ublinux-data/optional"
    local removeDir
    local modulesFolderName

    local nameModule="${argPathModule##*/}"
    local updatedPathModule="$mntLivedataPath/$ublinuxDataModules/${nameModule%.*}.$(date +'%Y%m%d').ubm"
    local name=""
    local date=""
    local order=""
    local findModule=""
    local checkUpdate="false"

    if [ -n "$(echo "$nameModule" | grep -E "^[0-9]{3}-[0-9]{4}-.[a-zA-Z_-]+\.ubm$")" ]; then
        name="$(echo "$nameModule" | sed -E 's/^[0-9]+-[0-9]+-//')"
        date="$(echo "$nameModule" | sed -E 's/^[0-9]+-//' | sed 's/-[a-zA-Z_-]*\.ubm//')"
        order="$(echo "$nameModule" | sed -E 's/-[0-9]+-[a-zA-Z_-]*\.ubm//')"
    elif [ -n "$(echo "$nameModule" | grep -E "^[0-9]{3}-[0-9]+\.[0-9]+\.[0-9]+[0-9-]*-[a-zA-Z_-]+\.ubm$")" ]; then
        name="$(echo "$nameModule" | sed -E 's/^[0-9]+-[0-9]+\.[0-9]+\.[0-9]+-[0-9]-//')"
        date="$(echo "$nameModule" | sed -E 's/^[0-9]+-//' | sed 's/-[a-zA-Z_-]*\.ubm$//')"
        order="$(echo "$nameModule" | sed -E 's/-[0-9]+\.[0-9]+\.[0-9]+-[0-9]-[a-zA-Z_-]*\.ubm$//')"
    elif [ -n "$(echo "$nameModule" | grep -E "^[0-9]{4}-(aur-)*[a-zA-Z_-]+\.ubm$")" ]; then
        name="$(echo "$nameModule" | sed -E 's/^[0-9]+-(aur-)*//')" #'
        date="$(echo "$nameModule" | sed -E 's/(aur-)*[a-zA-Z_-]*\.ubm$//')"
    else
        name="$nameModule"
    fi

    if [ -n "$order" ]; then
        findModule=($(find ${ALLPATH_MODULES} -name "$order" ))
        [ -n "${findModule[0]}" ] && [ -n "$(echo "${findModule[0]}" | grep "$name")" ] && \
        findModule="${findModule[0]}" || findModule=""
        [ -n "$findModule" ] && ([ -n "$(echo "$findModule" | grep "$date")" ] && checkUpdate="false" || checkUpdate="true")
    elif [ -n "$date" ]; then
        findModule=($(find ${ALLPATH_MODULES} -name "*$name" ))
        [ -n "${findModule[0]}" ] && findModule="${findModule[0]}" || findModule=""
        [ -n "$findModule" ] && [ -n "$(echo "$findModule" | grep "$date")" ] && checkUpdate="false" || checkUpdate="true"
    else
        findModule=($(find ${ALLPATH_MODULES} -name "$name" ))
        [ -n "${findModule[0]}" ] && findModule="${findModule[0]}" || findModule=""
    fi

    if [ -z "$findModule" ]; then
        ([ -n "$(echo "$nameModule" | grep -E "^[0-9]{3}-[0-9]{4}-.[a-zA-Z_-]+\.ubm$")" ] || \
            [ -n "$(echo "$nameModule" | grep -E "^[0-9]{3}-[0-9]+\.[0-9]+\.[0-9]+[0-9-]*-[a-zA-Z_-]+\.ubm$")" ]) \
            && modulesFolderName="base" || modulesFolderName="modules"
        
        rCode="1"
        for i in $(find ${ublinux_data_path_root} -maxdepth 1 -type d -iname $modulesFolderName); do
		    if [ -w ${i} ]; then
		        cp -f "${argPathModule}" "${i}" && eval ${BIN_MODLOAD} ${i}/${nameModule} && \
		            eval ${GETLAYER} --raw | grep -s $nameModule && rCode="0" || rCode="1"
		        echo "${i}/$nameModule" > "$tmpChangeName"
		        break
		    fi
	    done

        if [ "$rCode" == "0" ]; then
            for deletedModuleFolder in $(find ${ALLPATH_DELETED_MODULES} -maxdepth 1 -type f -iname ${nameModule}); do
                if [ -w ${deletedModuleFolder} ]; then
                    rm -f ${deletedModuleFolder} && rCode="0" || rCode="1"
                    break
                fi
            done
        fi
    elif [ -n "$findModule" ]; then
        [ "$checkUpdate" == "false" ] && message="$(i18n "The system already has this module.%sUpdate now?" "\n")" || \
            message="$(i18n "This module is already in the system,%sbut from another update branch.%sThe system needs to be updated!%sContinue?" "\n" "\n" "\n")"

        yad --center \
            --title="$(i18n "Warning")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-yes:0" \
            --button="yad-no:1" \
            --width="205" \
            --text="$message"
        [ "$?" == 1 ] && return 1

        [ -n "$(echo "$findModule" | grep $ublinux_data_path_root*)" ] && removeDir="$mntLivedataPath/$ubLinuxDataOptional" || \
            removeDir="$mntLivemediaPath/$ubLinuxOptional"

        for i in $(find $ALLPATH_MODULES -iname ${nameModule%.*}* | (sed -u 1q; sort)); do
            eval ${BIN_MODUNLOAD} "$i" &>/dev/null
            eval ${GETLAYER} --raw | grep -s $(basename $i) && rCode="1" || rCode="0"

            if [ "$rCode" == "0" ]; then
                mv -f "$i" "$removeDir" && rCode="0" || rCode="1"
                [ "$rCode" == "1" ] && break
            else
                yad --center \
                    --title="$(i18n "Warning")" \
                    --window-icon=ublinux-ubmodulemenu \
                    --button="$(i18n "Continue"):0" \
                    --button="yad-cancel:1" \
                    --width="205" \
                    --text="$(i18n "The module is busy!%sClick continue for automatic%supdate after reboot." "\n" "\n")"
                [ "$?" == "1" ] && return 1

                cp -f "$argPathModule" "$updatedPathModule" && rCode="0" || rCode="1"
                [ "$rCode" == "0" ] && yad --center \
                        --title="$(i18n "Done")" \
                        --window-icon=ublinux-ubmodulemenu \
                        --button="$(i18n "Yes"):0" \
                        --button="$(i18n "No"):1" \
                        --width="205" \
                        --text="$(i18n "Perform a system reboot?")"
                [ "$?" == "0" ] && systemctl reboot && return 0

                [ "$rCode" == 0 ] && \
                    yad --center \
                        --title="$(i18n "Done")" \
                        --window-icon=ublinux-ubmodulemenu \
                        --button="yad-ok:0" \
                        --width="205" \
                        --text="$(i18n "Install complete!")" && return 0
                break
            fi
        done
        
        if [ "$rCode" == "0" ]; then
            cp -f "$argPathModule" "$findModule" && eval ${BIN_MODLOAD} "$findModule" && \
                eval ${GETLAYER} --raw | grep -s "$findModule" && rCode="0" || rCode="1"
            echo "$findModule" > "$tmpChangeName"
        fi
    fi

    [ "$rCode" == 0 ] && \
        yad --center \
            --title="$(i18n "Done")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Install complete!")" && return 0 || \
        yad --center \
            --title="$(i18n "Error")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Install error!")" && return 1
}
export -f run_install_module

run_remove_module(){
    local ublinuxBase="ublinux/base"
    local ublinuxModules="ublinux/modules"
    local ublinuxDataModules="ublinux-data/modules"
    local ubLinuxOptional="ublinux/optional"
    local ubLinuxDataOptional="ublinux-data/optional"

    local removeDir
    local installedModulePath
    local pathModule="${argPathModule%/*}"
    local nameModule=$(basename "$argPathModule" | cut -f 1 -d '.')

    local deletedModules=()
    local busyModules=()
    local disabledModuleNames="$(i18n "The modules is deleted: %s")"
    local busyModulesNames="$(i18n "The modules is busy: %s")"
    local modulesInformation

    yad --center \
        --title="$(i18n "Warning")" \
        --window-icon=ublinux-ubmodulemenu \
        --button="yad-yes:0" \
        --button="yad-no:1" \
        --width="205" \
        --text="$(i18n "Are you sure you want to delete the module?")"
    [ "$?" == "1" ] && return 1

    if [ -n "$(find "$mntLivemdeiaPath/$ublinuxModules" -iname $nameModule*)" ]; then
        installedModulePath="$mntLivemdeiaPath/$ublinuxModules"
        removeDir="$mntLivemdeiaPath/$ubLinuxOptional"
    elif [ -n "$(find "$mntLivemdeiaPath/$ublinuxBase" -iname $nameModule*)" ]; then
        installedModulePath="$mntLivemdeiaPath/$ublinuxBase"
        removeDir="$mntLivemdeiaPath/$ubLinuxOptional"
    elif [ -n "$(find "$mntLivemdeiaPath/$ublinuxDataModules" -iname $nameModule*)" ]; then
        installedModulePath="$mntLivedataPath/$ublinuxDataModules"
        removeDir="$mntLivedataPath/$ubLinuxDataOptional"
    fi

    rCode="1"
    for i in $(find $installedModulePath -iname ${nameModule}* | (sed -u 1q; sort)); do
        eval ${BIN_MODUNLOAD} "$i" &>/dev/null
        eval ${GETLAYER} --raw | grep -s $(basename $i) && rCode="1" || rCode="0"

        if [ "$rCode" == "0" ]; then
            deletedModules+=("$i")
            [ -n "$removeDir" ] && mv -f "$i" "$removeDir" && rCode="0" || rCode="2"
            [ "$rCode" == "2" ] && break
        else
            busyModules+=("$i")
        fi
    done

    if [ "${#busyModules[*]}" != "0" ]; then
        for deletedModule in ${deletedModules[@]}; do disabledModuleNames+="\n$(basename $deletedModule)"; done
        for busyModule in ${busyModules[@]}; do busyModulesNames+="\n$(basename $busyModule)"; done

        if [ ${#deletedModules[*]} == "0" ]; then modulesInformation="$busyModulesNames"
        else modulesInformation="$disabledModuleNames\n\n$busyModulesNames"; fi
        
        yad --center \
            --title="$(i18n "Warning")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text-width="24" \
            --text="$(echo "$modulesInformation")"

        yad --center \
            --title="$(i18n "Warning")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="$(i18n "Yes"):0" \
            --button="$(i18n "No"):1" \
            --width="205" \
            --text="$(i18n "Are you want to force delete the modules?")"

        if [ "$?" == "0" ]; then
            for i in ${busyModules[@]}; do
                [ -n "$removeDir" ] && mv -f "$i" "$removeDir" && rCode="0" || rCode="1"
            done

            yad --center \
                --title="$(i18n "Done")" \
                --window-icon=ublinux-ubmodulemenu \
                --button="$(i18n "Yes"):0" \
                --button="$(i18n "No"):1" \
                --width="205" \
                --text="$(i18n "Perform a system reboot?")"
            [ "$?" == "0" ] && systemctl reboot && return 0
        else
            rCode="1"
        fi
    fi

    [ "$rCode" == "0" ] && \
        yad --center \
            --title="$(i18n "Done")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Remove complete!")"

    [ "$rCode" == "1" ] && \
        yad --center \
            --title="$(i18n "Error")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "Error deleting the module!")" && return 1

    [ "$rCode" == "2" ] && \
        yad --center \
            --title="$(i18n "Error")" \
            --window-icon=ublinux-ubmodulemenu \
            --button="yad-ok:0" \
            --width="205" \
            --text="$(i18n "The module was unloaded, but not deleted!")"
}
export -f run_remove_module

main_menu(){
    local pathModule="$1"
    local nameModule="${pathModule##*/}"
    local realPathModule="${pathModule%/*}"
    local typeModule=""
    if [ -n "$(echo "$nameModule" | grep -E "^[0-9]{3}-[0-9]{4}-.[a-zA-Z_-]+\.ubm$")" ]; then
        name="$(echo "$nameModule" | sed -E 's/^[0-9]+-[0-9]+-//')"
        date="$(echo "$nameModule" | sed -E 's/^[0-9]+-//' | sed 's/-[a-zA-Z_-]*\.ubm//')"
        date="${date:2}.20${date::-2}"
        order="$(echo "$nameModule" | sed -E 's/-[0-9]+-[a-zA-Z_-]*\.ubm//')"

        descModule="$(i18n "Module name: %s, date version: %s, load order: %s." "${name%%.*}" "$date" "$order")"
    elif [ -n "$(echo "$nameModule" | grep -E "^[0-9]{3}-[0-9]+\.[0-9]+\.[0-9]+[0-9-]*-[a-zA-Z_-]+\.ubm$")" ]; then
        name="$(echo "$nameModule" | sed -E 's/^[0-9]+-[0-9]+\.[0-9]+\.[0-9]+-[0-9]-//')"
        ver="$(echo "$nameModule" | sed -E 's/^[0-9]+-//' | sed 's/-[a-zA-Z_-]*\.ubm$//')"
        order="$(echo "$nameModule" | sed -E 's/-[0-9]+\.[0-9]+\.[0-9]+-[0-9]-[a-zA-Z_-]*\.ubm$//')"

        descModule="$(i18n "Module name: %s, version: %s, load order: %s." "${name%%.*}" "$ver" "$order")"
    elif [ -n "$(echo "$nameModule" | grep -E "^[0-9]{4}-(aur-)*[a-zA-Z_-]+\.ubm$")" ]; then
        name="$(echo "$nameModule" | sed -E 's/^[0-9]+-(aur-)*//')" #'
        aur="$(echo "$nameModule" | sed -E 's/^[0-9]+-//' | sed -E 's/-[a-zA-Z_-]*\.ubm$//')"
        date="$(echo "$nameModule" | sed -E 's/(aur-)*[a-zA-Z_-]*\.ubm$//')"
        date="${date:2}.20${date::-2}"

        if [ "$aur" == "aur" ]; then
            descModule="$(i18n "AUR module: %s, date version: %s." "${name%%.*}" "$date")"
        else
            descModule="$(i18n "Module: %s, date version: %s." "${name%%.*}" "$date")"
        fi
    else
        descModule="$(i18n "Module: %s." "${nameModule%%.*}")"
    fi
    
    [ -n "$(aufs-n --raw 2>/dev/null | grep $nameModule)" ] && dwnldModuleCmd="@disabled@" || unldModuleCmd="@disabled@"
    [ -z "$(find ${ALLPATH_MODULES} -iname ${nameModule%.*}*)"] && removeModuleCmd="@disabled@"

    yad --plug="${fkey}" \
        --tabnum=1 \
        --form \
        --no-markup \
        --columns=1 \
        --field="$(i18n "Connect the module"):fbtn" "${dwnldModuleCmd}" \
        --field="$(i18n "Disable the module"):fbtn" "${unldModuleCmd}" \
        --field="$(i18n "Install the module in the system"):fbtn" "${installModuleCmd}" \
        --field="$(i18n "Remove a module from the system"):fbtn" "${removeModuleCmd}" &>/dev/null &
        # --field="":lbl "" \
        # --field="$(i18n "Update"):fbtn" "${updInterface}" &>/dev/null &

    echo "${descModule:-Информация о модуле}" | \
        yad --plug="${fkey}" \
            --tabnum=2 \
            --text-info \
            --text="$(i18n "Information about the module")" \
            --wrap \
            --listen &>/dev/null &

    yad --plug="${fkey}" \
        --tabnum=3 \
        --list \
        --no-markup \
        --text "$(i18n "List of modules"):" \
        --column="$(i18n "Name")"  \
        --column="$(i18n "Description")"  \
        --search-column=1 \
        --expand-column=1 <&3 &>/dev/null &
            
    yad --notebook \
        --center \
        --key="${fkey}" \
        --tab="$(i18n "Settings")" \
        --tab="$(i18n "About the module")" \
        --tab="$(i18n "List of packages")" \
        --button="$(i18n "Update status"):1" \
        --button="yad-close:0" \
        --width=400 \
        --height=500 \
        --window-icon=ublinux-ubmodulemenu \
        --image=ublinux-ubmodulemenu \
        --text="$(i18n "Module management %s" "${nameModule}")" \
        --title="$(i18n "Module management")"
    
    retCode="$?"
    case "$retCode" in
        "0") return 0;;
        "1") "${updInterface}";;
        "252") return 0;;
        *) return 1;;
    esac
}
export -f main_menu

fill_data()(
    local pathModule="$1"
    local nameModule="$(basename "${pathModule%.*}")"
    local tmpModulePath="/tmp/$(mktemp -d ubmodulemenu.XXXX)/$nameModule"
    local submodulesPath="$tmpModulePath/var/lib/pacman/local"

    mkdir -p "$tmpModulePath" && mount "$pathModule" "$tmpModulePath"

    get_pkg_field(){
        local pkgFieldName="$1"
        local pkgDescPath="$2"
        local pkgDescValue=$(sed "/$pkgFieldName/,/%/ !d" $pkgDescPath | tail -n +2 | head -n -1)
        echo "$pkgDescValue"
    }

    for i in $(ls "$submodulesPath"); do
        local packageName=$(get_pkg_field "%NAME%" "$submodulesPath/$i/desc")
        local packageDesc=$(get_pkg_field "%DESC%" "$submodulesPath/$i/desc")
        #local packageDepends=$(get_pkg_field "%DEPENDS%" "$submodulesPath/$i/desc")
        
        echo -e "$packageName|$packageDesc" | sed 's/|/\n/g' >> "$pipe"
        echo "#$(i18n "Please wait")"
        sleep 0.5
    done | \
        yad --progress \
        --title="$(i18n "Generate data")" \
        --auto-close \
        --no-buttons \
        --pulsate \
        --width=350 \
        --height=50 \
        --window-icon=ublinux-ubmodulemenu \
        --auto-kill
)
export -f fill_data

choose_ubm(){
    answ=$(yad --file \
               --title "$(i18n "Select the module file")" \
               --width=800 \
               --window-icon=ublinux-ubmodulemenu \
               --file-filter="$(i18n "Module file") (*.ubm)| *.ubm" \
               --file-filter="$(i18n "All Files") | *.*" \
               --height=500)
    
    retVal="$?"
    case "$retVal" in
        0)
            [[ "$answ" == *".ubm" ]] && export argPathModule="$answ" && return 0 || \
                yad --center \
                    --title="$(i18n "Warning")" \
                    --window-icon=ublinux-ubmodulemenu \
                    --button="yad-ok:0" \
                    --text="$answ $(i18n "it is not a module!%sPlease select the .ubm file." "\n")"
        ;;
        *)
            return 2
        ;;
    esac
    return 1
}
export -f choose_ubm

exit_cmd()
{
    rm -f "$pipe" "$tmpChangeName"
    exec 3>&-
}
export -f exit_cmd

exec 3<>"$pipe"

while [[ -n $1 ]]; do
    case $1 in
        -h | --help)
            argHelp="-h"
        ;;
        *)
            [ -f "$1" ] && export argPathModule="$1"
        ;;
    esac
	shift
done

[ -n "${argHelp}" ] && echo -e "$(i18n "${msg_help}" "$(basename $0)")\n" && exit 0

if [ -n "${argPathModule}" ] && [[ "${argPathModule}" == *".ubm" ]] ; then
    fill_data "${argPathModule}"
    main_menu "${argPathModule}"
else
    while true; do
        choose_ubm
        rVal="$?"
        [ "$rVal" == "0" ] || [ "$rVal" == "2" ] && break
    done
    if [ "$rVal" == "0" ]; then
        fill_data "${argPathModule}"
        main_menu "${argPathModule}"
    fi
fi

exec 3>&-
exit 0
