#!/usr/bin/env bash

VERSION_SCRIPT=1.28

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

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

init(){
    OK_C=0
    CANCEL_C=1
    ESC_C=255

    path_root=""
    error=""
    path=""
    result=""
    export chk_cups_save="@disabled@"
    export chk_cpro_save="@disabled@"
    export chk_nmctl_save="@disabled@"

    export memoryPath="/memory"
    export mntLivemdeiaPath="/mnt/livemedia"
    export mntLivedataPath="/mnt/livedata"
    export chngsPath="/memory/changes"
    export cupsPath="etc/cups"
    export printcupPath="etc/printcap"
    export crpoPath="var/opt/cprocsp"
    export mnctlPath="etc/NetworkManager/system-connections"
    export varSmbPath="var/lib/samba"
    export etcSmbPath="etc/samba"
    export etcPasswdPath='etc/passwd'
    export etcShadowPath='etc/shadow'
    export etcGroupPath='etc/group'
    export etcGshadowPath='etc/gshadow'
    export changesUbdata='/mnt/livemedia/ublinux-data/changes'
    
    export TEXTDOMAIN=$(basename ${0%})
    export TEXTDOMAINDIR="${path_root}/usr/share/locale"

    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 dialog && DIA="dialog --aspect 20 " && DIA_ESC=-- && break
    type_file gdialog && DIA=gdialog && break
    exec date +%F $(i18n "No Dialog program found!")
    done

    [ -d "$chngsPath/$cupsPath" ] && [ -f "$chngsPath/$printcupPath" ] && chk_cups_save="no"
    [ -d "$chngsPath/$crpoPath" ] && chk_cpro_save="no"
    [ -d "$chngsPath/$mnctlPath" ] && chk_nmctl_save="no"
}
export -f init
init

error_without_root_dirs(){
    case "$1" in
        "gui")
            yad --center \
                --title="$(i18n "Error")" \
                --window-icon="ubbackupos" \
                --button="yad-ok:0" \
                --text="$(i18n "Unable to find the %s directory" "$2")"
            clear
        ;;
        "cli")
            dialog --backtitle "$(i18n "Backup and restore")" \
                 --title "$(i18n "Error")" \
                 --msgbox "$(i18n "Unable to find the %s directory" "$2")" 0 0
            clear
        ;;
    esac
    exit 1
}
export -f error_without_root_dirs

[[ -z $1 ]] && set - "-cli"

if [[ $@ != '-h' ]]; then
    if xhost &>/dev/null; then
        [ ! -d "$memoryPath" ] && error_without_root_dirs "gui" "/memory"
        [ ! -d "$mntLivemdeiaPath" ] && error_without_root_dirs "gui" "/mnt/livemedia"
        [ ! -d "$mntLivedataPath" ] && error_without_root_dirs "gui" "/mnt/livedata"
        [ $(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
    else
        [ ! -d "$memoryPath" ] && error_without_root_dirs "cli" "/memory"
        [ ! -d "$mntLivemdeiaPath" ] && error_without_root_dirs "cli" "/mnt/livemedia"
        [ ! -d "$mntLivedataPath" ] && error_without_root_dirs "cli" "/mnt/livedata"
        [ -n "$(echo "$@" | grep 'gui')" ] && echo -e "$(i18n "%sError:%s Script is running in terminal without X session with -gui key!%sThis session is not available, but you can use the key -cli!" "\e[1;31m" "\e[0m" "\\n")" && 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")" && su root -c "$(which $0) $@" && exit -1
        [ $(id -u) != 0 ] && exit -1
    fi
fi

trap 'menu_exit' SIGINT

fkey=$(($RANDOM))

export tmpChooseModule=$(mktemp -p /dev/shm)
export excludeFiles=$(mktemp -p /dev/shm)
export excludeFilesHome=$(mktemp -p /dev/shm)
export tmpChooseUsers=$(mktemp -p /dev/shm)
export chooserUsers=$(mktemp -p /dev/shm)
export tmpExitCodeMain=$(mktemp -p /dev/shm)
export save_cmd='@bash -c "run_save %1 %4 %5 %6 %7 %8 %9 %10 %11"'
export clear_cmd='@bash -c "run_clear save"'
export del_modul_cmd='@bash -c "run_del_modul"'
export choose_user_cmd='@bash -c "choose_user"'
export clear_changes_cmd='@bash -c "run_clear sys"'

export exceptDirsAndFilesHome=".cache
public
usershares
.Xauthority
.vboxclient*
.wh*"

export exceptDirsAndFiles="boot
home
memory
mnt
media
root
dev
proc
sys
tmp
lost+found
run
var/cache
var/db
var/lock
var/log
var/mail
var/run
var/spool
var/tmp
var/.updated
var/lib/pacman/sync
var/lib/systemd
etc/.updated
etc/brlapi.key
etc/group-
etc/gshadow-
etc/hostname
etc/hosts
etc/lsb-release
etc/ld.so.cache
etc/passwd-
etc/resolv.conf*
etc/shadow-
etc/ublinux-release
etc/vconsole.conf
etc/locale.conf
etc/initvars
etc/ublinux
var/lib/samba/private/msg.sock
etc/mtab
usr/lib/os-release
usr/lib/gdk-pixbuf-*/*/*.cache
usr/share/applications/mimeinfo.cache
usr/share/backgrounds/*
var/cache/fontconfig
usr/share/fonts/TTF/fonts.dir
usr/share/fonts/TTF/fonts.scale
usr/share/glib-2.0/schemas/gschemas.compiled
usr/share/icons/*/*.cache
usr/share/mime
usr/local/share/applications/mimeinfo.cache
var/cache/ldconfig
var/cache/man
.wh*"
echo "$exceptDirsAndFiles" > "$excludeFiles"
echo "$exceptDirsAndFilesHome" > "$excludeFilesHome"


msg_version="ubsave, version %s
Copyright (C) 2020 Ubiteh, Inc.
License GPLv3+: GNU GPL version 3 or later <http://ublinux.ru>"

msg_help="UBSave console application for saving settings

    Usage:    %s [-cli -gui] (-cups, -cpro, -nmctl, -home, -home-user *username*, -all) [-rc -modules]

    -h | --help
        Show a help message
    -cli
        Start with command line interface
    -gui
        Start with graphical user interface (not working w/o X session!)
    -cups | --save-cups
        Save the settings of the installed printers
    -cpro | --savescpro
        Save CryptoPro settings
    -nmctl | --savenetwork
        Save network interface settings
    -smb | --samba
        Save Samba Settings
    -psswd | --passwd-group
        Save group and user settings
    -home | --savehomes
        Save changes from all home folders
    -home-user *username*
        Save changes from the home directories of user
    -all | --saveall
        Save all system changes
    -rc
        Save to the user's changes directory (/ublinux-data/rootcopy)
    -modules
        Save in the user module (/ublinux-data/modules)
"

menu() {
    $DIA "$@" 3>&1 1>&2 2>&3
}

run_save(){
    local result
    if [ -n "${arg_cli}" ];then
        local args="${1}"
        main ${args}
        result="$?"
        [[ "${result}" == "0" ]] && \
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                    --title "$(i18n "Complete")" \
                    --msgbox "$(i18n "Save completed!")" 0 0 && return 0
        [[ "${result}" == "1" ]] && \
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                    --title "$(i18n "Error")" \
                    --msgbox "$(i18n "Save error!")" 0 0 && return 1
        [[ "${result}" == "2" ]] && \
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                    --title "$(i18n "Error")" \
                    --msgbox "$(i18n "Saving to the user's changes directory is not possible! Please check your access rights.")" 0 0 && return 1
        [[ "${result}" == "3" ]] && \
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                    --title "$(i18n "Error")" \
                    --msgbox "$(i18n "Saving to the user module is not possible! Please check your access rights.")" 0 0 && return 1
        [[ "${result}" == "4" ]] && \
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                    --title "$(i18n "Error")" \
                    --msgbox "$(i18n "Saving is not possible! Please check your access rights.")" 0 0 && return 1
        [[ "${result}" == "5" ]] && \
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                    --title "$(i18n "Warning")" \
                    --msgbox "$(i18n "The changes cannot be saved to the user's%schange directory(/ublinux-data/rootcopy)%sThe size of the changes exceeds the allowed volume." "\n" "\n")" 0 0 && return 1
    fi

    if [ -n "${arg_gui_yad}" ];then
        local checkRcToSaveUser="false"
        if [ -n "$(echo "$1" | grep "rootcopy")" ]; then
            checkRcToSaveUser="true"
            args+="-rc "
        elif [ -n "$(echo "$1" | grep "modules")" ]; then
            args+="-modules "
        fi
        if [ "$2" = "TRUE" ]; then
            args+="-cups "
        fi
        if [ "$3" = "TRUE" ]; then
            args+="-cpro "
        fi
        if [ "$4" == "TRUE" ]; then
            args+="-nmctl "
        fi
        if [ "$5" == "TRUE" ]; then
            args+="-smb "
        fi
        if [ "$6" == "TRUE" ]; then
            args+="-psswd "
        fi
        if [ "$7" == "TRUE" ]; then
            [ "$checkRcToSaveUser" == "true" ] && \
                yad --center \
                    --title="$(i18n "Warning")" \
                    --window-icon="ublinux-ubsave" \
                    --button="yad-ok:0" \
                    --text="$(i18n "It is impossible to save changes to the users%s'home directories to the users' change directory!" "\n")" && return 1
            args+="-home "
        fi
        if [ "$8" == "TRUE" ]; then
            [ "$checkRcToSaveUser" == "true" ] && \
                yad --center \
                    --title="$(i18n "Warning")" \
                    --window-icon="ublinux-ubsave" \
                    --button="yad-ok:0" \
                    --text="$(i18n "It is impossible to save changes to the users%s'home directories to the users' change directory!" "\n")" && return 1
            choose_user || return 1
            args+="-home-user "
        fi
        if [ "$9" == "TRUE" ]; then
            args+="-all "
        fi

        (
            echo "#$(i18n "Please wait")"
            main ${args} & pcs=$!
            progress "$pcs" & wait $pc1
            echo "$?" > "$tmpExitCodeMain"
            sleep 0.2
        ) | yad --progress \
                --title="$(i18n "Saving changes")" \
                --pulsate \
                --auto-close \
                --no-buttons \
                --height=50 \
                --window-icon="ublinux-ubsave" \
                --width=250

        result="$(cat "$tmpExitCodeMain")"
        [[ "${result}" == "0" ]] && \
            yad --center \
                --title="$(i18n "Complete")" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "Save completed!")"
        [[ "${result}" == "1" ]] && \
            yad --center \
                --title="$(i18n "Error")" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "Save error!")"
        [[ "${result}" == "2" ]] && \
            yad --center \
                --title="$(i18n "Error")" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "Saving to the user's changes directory is not possible! Please check your access rights.")"
        [[ "${result}" == "3" ]] && \
            yad --center \
                --title="$(i18n "Error")" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "Saving to the user module is not possible! Please check your access rights.")"
        [[ "${result}" == "4" ]] && \
            yad --center \
                --title="$(i18n "Error")" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "Saving is not possible! Please check your access rights.")"
        [[ "${result}" == "5" ]] && \
            yad --center \
                --title="$(i18n "Warning")" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "The changes cannot be saved to the user's%schange directory(/ublinux-data/rootcopy)%sThe size of the changes exceeds the allowed volume." "\n" "\n")"
#"
    fi
}
export -f run_save

progress(){
    local i=0
    while ps $1 > /dev/null ; do
        echo $((i++))
        sleep 0.1
    done
}
export -f progress

choose_user(){
    echo -n > "$tmpChooseUsers"
    local arrUsers
    local i=1000
    local _CHOOSER=''
    if [ -n "${arg_gui_yad}" ]; then
        while read -r line; do
            if [ "$(echo "$line" | cut -d ':' -f3)" -ge "1000" ] && [ "$(echo "$line" | cut -d ':' -f1)" != "nobody" ]; then
                echo "$line" | cut -d ':' -f1 | awk -v chk=false '{print chk"\n"$0}'
            fi
        done < <(getent passwd) | \
            yad --list \
                --title="$(i18n "Choose users")" \
                --checklist \
                --print-all \
                --no-selection \
                --text "$(i18n "You have selected \"Save the user's home directory\"%sSelect the users whose home directory you want to save:" "\n")" \
                --column="" \
                --column="$(i18n "User")" \
                --window-icon="ublinux-ubsave" \
                --width=260 \
                --height=290 \
                --search-column=1 \
                --button="yad-cancel:1" \
                --button="yad-ok:0" \
                --expand-column=0 > "$tmpChooseUsers"
        
        r_val="$?"
        case "$r_val" in
            "1")
                return 1
            ;;
            "0")
                while read -r l; do
                    if [ "$(echo "$l" | awk -F'|' '{print $1}')" == "TRUE" ]; then
                        _CHOOSER+="$(echo "$l" | awk -F'|' '{print $2}'), "
                    fi
                done < <(cat "$tmpChooseUsers")

                if [ -n "$(echo "$_CHOOSER" | grep ", $")" ]; then
                    echo "${_CHOOSER::-2}" > "$chooserUsers"
                else
                    echo "$_CHOOSER" > "$chooserUsers"
                fi
                return 0
            ;;
        esac
    fi

    if [ -n "${arg_cli}" ]; then
        while read -r line; do
            if [ "$(echo "$line" | cut -d ':' -f3)" -ge "1000" ] && [ "$(echo "$line" | cut -d ':' -f1)" != "nobody" ]; then
                arrUsers+=("$(echo "$line" | cut -d ':' -f3) $(echo "$line" | cut -d ':' -f1) no")
            fi
        done < <(getent passwd)

        menu --backtitle "$(i18n "Managing the saving of changes")" \
             --title "$(i18n "Choose users")" \
             --cancel-label "$(i18n "Back")" \
             --clear \
             --no-collapse \
             --tab-correct \
             --checklist "$(i18n "Select users")" 0 0 0 \
             ${arrUsers[@]} > "$tmpChooseUsers"
        
        return_value="$?"
        case "$return_value" in
            "$OK_C")
                answUidUsers=($(cat "$tmpChooseUsers"))
                if [ -z "${answUidUsers[@]}" ]; then
                    menu --backtitle "$(i18n "Managing the saving of changes")" \
                        --title "$(i18n "Error")" \
                        --msgbox "$(i18n "Select a user!")" 0 0 && return 1
                else
                    for i in ${answUidUsers[@]}; do
                        _CHOOSER+="$(getent passwd $i | cut -d ':' -f1), "
                    done
                    if [ -n "$(echo "$_CHOOSER" | grep ", $")" ]; then
                        echo "${_CHOOSER::-2}" > "$chooserUsers"
                    else
                        echo "$_CHOOSER" > "$chooserUsers"
                    fi
                    while true; do dir_select_cli 7 && break; done
                    return 0
                fi
            ;;
            "$CANCEL_C") return 0;;
            "$ESC_C") return 0;;
        esac
        return 1
    fi

}
export -f choose_user

run_clear(){
    if [ "$1" == "sys" ]; then
        local arg_rc_path=""
        [ -d "$changesUbdata" ] && arg_rc_path="$changesUbdata" || arg_rc_path="$chngsPath"
        local checkRm="0"
    elif [ "$1" == "save" ]; then
        local arg_rc_path=($(realpath /memory/layer-base/*/rootcopy))
        local arg_rc_path=${arg_rc_path[${#arg_rc_path[@]}-1]}
    fi
    if [ -n "${arg_gui_yad}" ]; then
        answere="$(yad --center \
            --title="$(i18n "Warning!")" \
            --window-icon="ublinux-ubsave" \
            --button="yad-ok:0" \
            --button="yad-cancel:1" \
            --text="$(i18n "You want to clear the save change directory.%sThus, all saved changes will be lost.%sAre you sure?" "\n" "\n")")"
        local r_val=$?

        case "$r_val" in
            0)
                if [ "$1" == "sys" ]; then
                    #if [ -n "$(mount | grep "changes")" ]; then
                    #    cd "${arg_rc_path}"
                    #    while read -r line; do
                    #        pathFileDel+=($line)
                    #        [ "$checkRm" == "1" ] && break
                    #    done < <(find -type f -not \( -path './.wh.*' \) | sed 's|./|/|')
                    #    rm -f ${pathFileDel[@]} && checkRm="0" || checkRm="1"
                    #else
                    #    arg_rc_path=($(realpath /memory/layer-base/*/changes))
                    #    arg_rc_path=${arg_rc_path[${#arg_rc_path[@]}-1]}
                    #    [ -n "$arg_rc_path" ] && rm -rf ${arg_rc_path}/* &>/dev/null && checkRm="0" || checkRm="1"
                    #fi
                    ubconfig --quiet set [save] SAVE_CLEAN=changes
                    #[ "$checkRm" == "0" ] && \
                        yad --center \
                            --title="$(i18n "Complete")" \
                            --window-icon="ublinux-ubsave" \
                            --button="yad-ok:0" \
                            --text="$(i18n "All changes have been deleted")" || \
                        yad --center \
                            --title="$(i18n "Error")" \
                            --window-icon="ublinux-ubsave" \
                            --button="yad-ok:0" \
                            --text="$(i18n "Failed to delete changes")"
                elif [ "$1" == "save" ]; then
                    ubconfig --quiet set [save] SAVE_CLEAN=rootcopy
                    #[ -n "$arg_rc_path" ] && rm -rf ${arg_rc_path}/* && \
                        yad --center \
                            --title="$(i18n "Complete")" \
                            --window-icon="ublinux-ubsave" \
                            --button="yad-ok:0" \
                            --text="$(i18n "All saved changes have been deleted")" || \
                        yad --center \
                        --title="$(i18n "Error")" \
                        --window-icon="ublinux-ubsave" \
                        --button="yad-ok:0" \
                        --text="$(i18n "Failed to delete saved changes")"
                fi
            ;;
        esac
    fi

    if [ -n "${arg_cli}" ]; then
        menu --backtitle "$(i18n "Managing the saving of changes")" \
             --title "$(i18n "Warning")" \
             --cancel-label "$(i18n "Back")" \
             --clear \
             --no-collapse \
             --tab-correct \
             --yesno "$(i18n "You want to clear the save change directory.%sThus, all saved changes will be lost.%sAre you sure?" "\n" "\n")" 0 0

        return_value="$?"
        echo $return_value
        case "$return_value" in
            "$OK_C")
                if [ "$1" == "sys" ]; then
                    #if [ -n "$(mount | grep "changes")" ]; then
                    #    cd "${arg_rc_path}"
                    #    while read -r line; do
                    #        pathFileDel+=($line)
                    #    done < <(find -type f -not \( -path './.wh.* ' \) | sed 's|./|/|')

                    #    rm -f ${pathFileDel[@]} && checkRm="0" || checkRm="1"
                    #else
                    #    arg_rc_path=($(realpath /memory/layer-base/*/changes))
                    #    arg_rc_path=${arg_rc_path[${#arg_rc_path[@]}-1]}
                    #    [ -n "$arg_rc_path" ] && rm -rf ${arg_rc_path}/* &>/dev/null && checkRm="0" || checkRm="1"
                    #fi

                    ubconfig --quiet set [save] SAVE_CLEAN=changes
                    #[ "$checkRm" == "0" ] && \
                        menu --backtitle "$(i18n "Managing the saving of changes")" \
                             --title "$(i18n "Complete")" \
                             --msgbox "$(i18n "All changes have been deleted")" 0 0 && return 0 || \
                        menu --backtitle "$(i18n "Managing the saving of changes")" \
                             --title "$(i18n "Error")" \
                             --msgbox "$(i18n "Failed to delete changes")" 0 0 && return 0
                elif [ "$1" == "save" ]; then
                    ubconfig --quiet set [save] SAVE_CLEAN=rootcopy
                    #[ -n "$arg_rc_path" ] && rm -rf ${arg_rc_path}/* && \
                        menu --backtitle "$(i18n "Managing the saving of changes")" \
                             --title "$(i18n "Complete")" \
                             --msgbox "$(i18n "All saved changes have been deleted")" 0 0 && return 0 || \
                        menu --backtitle "$(i18n "Managing the saving of changes")" \
                             --title "$(i18n "Error")" \
                             --msgbox "$(i18n "Failed to delete saved changes")" 0 0 && return 0
                fi
            ;;
            "$CANCEL_C") return 0;;
            "$ESC_C") return 0;;
        esac
        return 0
    fi
    return
}
export -f run_clear


run_del_modul(){
    local arg_modules_path=($(realpath /memory/layer-base/*/modules))
    local arg_modules_path=${arg_modules_path[${#arg_modules_path[@]}-1]}
    local i=1
    local arrModules
    cd "$arg_modules_path"
    #local chkModule=("$(find . -regextype sed -regex "./[0-9]+\.[0-9]*\.[0-9]*[a-z,A-Z,0-9.-]*.ubm" | sed 's/\.\///')")
    local chkModule=("$(find . -regextype egrep -regex "\./[0-9]{8,8}\-[0-9]{4,4}\-(home|changes).*\.ubm" | sed 's/\.\///')") #"
    if [ -n "${chkModule[@]}" ]; then
        if [ -n "${arg_gui_yad}" ]; then
            for moduleName in ${chkModule[@]}; do
                echo "$moduleName" | awk -v chk="false" '{print chk"\n"$1}'
            done | \
                yad --list \
                    --title="$(i18n "Delete modules")" \
                    --checklist \
                    --print-all \
                    --no-selection \
                    --text "$(i18n "Select modules")" \
                    --column="" \
                    --column="$(i18n "Module")" \
                    --window-icon=ublinux-ubsave \
                    --button="yad-close:1" \
                    --button="yad-ok:0" \
                    --width=350 \
                    --height=450 \
                    --search-column=1 \
                    --expand-column=0 > "$tmpChooseModule"
            
            local r_val=$?

            case "$r_val" in
                0)
            	    local REMOVE_UBM_OK=
                    for line in $(cat ${tmpChooseModule}); do
                        if [[ "$(echo "$line" | awk -F'|' '{print $1}')" == "TRUE" ]]; then
                            ubmunload $(echo "$line" | awk -F'|' '{print $2}') &>/dev/null && REMOVE_UBM_OK=1 || REMOVE_UBM_OK=
                            mount | grep --quiet "$(echo "$line" | awk -F'|' '{print $2}')" && REMOVE_UBM_OK=
                            if [[ ${REMOVE_UBM_OK} == 1 ]]; then
                                rm -f "$arg_modules_path/$(echo "$line" | awk -F'|' '{print $2}')"
                            else
                                install -dm0750 ${arg_modules_path%/*}/upgrade/
                                echo "remove=${arg_modules_path}/$(echo "$line" | awk -F'|' '{print $2}')" >> ${arg_modules_path%/*}/upgrade/upgrade.conf
                            fi
                        fi
                    done
                    yad --center \
                        --title="$(i18n "Complete")" \
                        --window-icon="ublinux-ubsave" \
                        --button="yad-ok:0" \
                        --text="$(i18n "The modules have been removed")"
                ;;
            esac
        fi

        if [ -n "${arg_cli}" ]; then
            for moduleName in ${chkModule[@]}; do
                arrModules+=("$moduleName $(du -h $moduleName | awk '{print $1}') no")
            done
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                 --title "$(i18n "Delete modules")" \
                 --cancel-label "$(i18n "Back")" \
                 --clear \
                 --no-collapse \
                 --tab-correct \
                 --checklist "$(i18n "Select modules")" 0 0 0 \
                 ${arrModules[@]} > "$tmpChooseModule"

            return_value="$?"
            case "$return_value" in
                "$OK_C")
            	    local REMOVE_UBM_OK=
                    for line in $(cat ${tmpChooseModule}); do
                        #if [[ "$(echo "$line" | awk -F'|' '{print $1}')" == "TRUE" ]]; then
                            ubmunload "$line" &>/dev/null && REMOVE_UBM_OK=1 || REMOVE_UBM_OK=
                            mount | grep --quiet "$line" && REMOVE_UBM_OK=
                            if [[ ${REMOVE_UBM_OK} == 1 ]]; then
                                rm -f "$arg_modules_path/$line"
                            else
                                install -dm0750 ${arg_modules_path%/*}/upgrade/
                                echo "remove=${arg_modules_path%/*}/$line" >> "${arg_modules_path%/*}/upgrade/upgrade.conf"
                            fi
                        #fi
                    done
                    menu --backtitle "$(i18n "Managing the saving of changes")" \
                         --title "$(i18n "Complete")" \
                         --msgbox "$(i18n "The modules have been removed")" 0 0 && return 0
                ;;
                "$CANCEL_C") return 0;;
                "$ESC_C") return 0;;
            esac
            return 1
        fi
    else
        if [ -n "${arg_gui_yad}" ]; then
            yad --center \
                --title="" \
                --window-icon="ublinux-ubsave" \
                --button="yad-ok:0" \
                --text="$(i18n "There is nothing to delete!")"
        fi
        
        if [ -n "${arg_cli}" ]; then
            menu --backtitle "$(i18n "Managing the saving of changes")" \
                 --title "" \
                 --msgbox "$(i18n "There is nothing to delete!")" 0 0 && return 0
        fi
    fi
    return 1
}
export -f run_del_modul

main(){
    local tmpUblinuxChng="/tmp/ublinux/changes"
    rm -rdf "${tmpUblinuxChng}"

    declare -a chsUsers=($(cat "$chooserUsers" | sed 's/,//g'))
    local memTotalInByte="$(free -b | grep Mem | awk '{print $2}')"
    local accessMem="$(($memTotalInByte-1073741824))"
    local path="$chngsPath"

    while [[ -n $1 ]]; do
        case $1 in
            -cups | --save-cups)
                [ -n "$arg_rc_path" ] && (check_access_save "${path}/$cupsPath"  "${path}/$printcupPath" || return 5)
                arg_cups="-cups"
            ;;
            -cpro | --savescpro)
                [ -n "$arg_rc_path" ] && (check_access_save "${path}/$crpoPath" || return 5)
                arg_cpro="-cpro"
            ;;
            -rc)
                arg_rc_path="-rc"
            ;;
            -modules)
                arg_modules_path="-modules"
            ;;
            -nmctl | --savenetwork)
                [ -n "$arg_rc_path" ] && (check_access_save "${path}/$mnctlPath" || return 5)
                args_nmctl="-nmctl"
            ;;
            -smb | --samba)
                arg_smb="-smb"
            ;;
            -psswd | --passwd-group)
                arg_psswd="-psswd"
            ;;
            -home | --savehomes)
                [ -n "$arg_rc_path" ] && (check_access_save "/home" || return 5)
                args_home="-home"
                [ -z "${arg_cli}" ] && [ -z "${arg_gui_yad}" ] && arg_user="$2"
            ;;
            -home-user)
                for i in ${chsUsers[@]}; do
                    tmpStrUser+="/home${i} "
                done
                [ -n "$tmpStrUser" ] && tmpStrUser="${tmpStrUser::-1}"
                [ -n "$arg_rc_path" ] && (check_access_save $tmpStrUser || return 5)
                args_home_user="-home-user"
            ;;
            -all | --saveall)
                [ -n "$arg_rc_path" ] && (check_access_save "${path}" || return 5)
                args_all="-all"
            ;;
        esac
        shift
    done
    local chk_rghts_rc
    local chk_rghts_md
    local write_rule_rc
    local write_rule_md
    if [ -n "$arg_rc_path" ]; then
        arg_rc_path=($(realpath /memory/layer-base/*/rootcopy))
        arg_rc_path=${arg_rc_path[${#arg_rc_path[@]}-1]}
        write_rule_rc=$(stat -c "%a" "${arg_rc_path}")
        ([[ "${write_rule_rc::1}" == "7" ]] || [[ "${write_rule_rc::1}" == "2" ]] || [[ "${write_rule_rc::1}" == "6" ]] || [[ "${write_rule_rc::1}" == "3" ]] || [[ -z "${write_rule_rc}" ]]) && \
        chk_rghts_rc=1 || chk_rghts_rc=0
    fi

    if [ -n "$arg_modules_path" ]; then
        arg_modules_path=($(realpath /memory/layer-base/*/modules))
        arg_modules_path=${arg_modules_path[${#arg_modules_path[@]}-1]}
        write_rule_md=$(stat -c "%a" "${arg_modules_path}")
        ([[ "${write_rule_md::1}" == "7" ]] || [[ "${write_rule_md::1}" == "2" ]] || [[ "${write_rule_md::1}" == "6" ]] || [[ "${write_rule_md::1}" == "3" ]] || [[ -z "${write_rule_md}" ]]) && \
        chk_rghts_md=1 || chk_rghts_md=0
    fi

    local result_cups
    local result_cpro
    local result_ubm
    local result_nmctl
    local result_smb
    local result_psswd
    local result_home
    local result_home_user
    local result_all

    if [ "${chk_rghts_rc}" == "1" ];then

        if [ -n "${arg_rc_path}" ]; then

            if [ -n "${arg_cups}" ];then
                rm -rf "${arg_rc_path}/$cupsPath" "${arg_rc_path}/$printcupPath" &>/dev/null		
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$cupsPath" "${arg_rc_path}" &>/dev/null && result_cups=0 || result_cups=1
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$printcupPath" "${arg_rc_path}" &>/dev/null && result_cups=0 || result_cups=1
            fi

            if [ -n "${arg_cpro}" ];then
                rm -rf "${arg_rc_path}/$crpoPath" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$crpoPath" ${arg_rc_path} &>/dev/null && result_cpro=0 || result_cpro=1
            fi

            if [ -n "${args_nmctl}" ]; then
                rm -rf "${arg_rc_path}/etc/NetworkManager" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$mnctlPath" "${arg_rc_path}" &>/dev/null && result_nmctl=0 || result_nmctl=1
            fi

            if [ -n "${arg_smb}" ]; then
                rm -rf "${arg_rc_path}/$varSmbPath" "${arg_rc_path}/$etcSmbPath" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$varSmbPath" "${arg_rc_path}" &>/dev/null && result_smb=0 || result_smb=1
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcSmbPath" "${arg_rc_path}" &>/dev/null && result_smb=0 || result_smb=1
            fi

            if [ -n "${arg_psswd}" ]; then
                rm -rf "${arg_rc_path}/$etcPasswdPath" "${arg_rc_path}/$etcShadowPath" "${arg_rc_path}/$etcGroupPath" "${arg_rc_path}/$etcGshadowPath" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcPasswdPath" "${arg_rc_path}" &>/dev/null && result_psswd=0 || result_psswd=1
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcShadowPath" "${arg_rc_path}" &>/dev/null && result_psswd=0 || result_psswd=1
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcGroupPath" "${arg_rc_path}" &>/dev/null && result_psswd=0 || result_psswd=1
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcGshadowPath" "${arg_rc_path}" &>/dev/null && result_psswd=0 || result_psswd=1
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$varSmbPath" "${arg_rc_path}" &>/dev/null && result_psswd=0 || result_psswd=1
            fi

            if [ -n "${args_home}" ]; then
                rm -rf "${arg_rc_path}/home" &>/dev/null
                rsync -aAXruR --exclude-from="$excludeFilesHome" "/home" "${arg_rc_path}" &>/dev/null && result_home=0 || result_home=1
            fi

            if [ -n "${args_home_user}" ]; then
                for user in ${chsUsers[@]}; do
                    rm -rf "${arg_rc_path}/home/$user" &>/dev/null
                    rsync -aAXruR --exclude-from="$excludeFilesHome" "/home/$user" "${arg_rc_path}" &>/dev/null && result_home_user=0 || result_home_user=1
                done
            fi

            if [ -n "${args_all}" ]; then
                rm -rf "${arg_rc_path}/$path" &>/dev/null
                cd "${path}" && rsync -aAXruR --exclude-from="$excludeFiles" * "${arg_rc_path}" &>/dev/null && result_all=0 || result_all=1
            fi
        fi
    elif [ -z "${chk_rghts_rc}" ];then
        chk_rghts_rc=2
    else
        chk_rghts_rc=0
    fi

    if [ "${chk_rghts_md}" == "1" ]; then

        if [ -n "${arg_modules_path}" ]; then

            local path_tmp="$tmpUblinuxChng/$(date '+%Y%m%d-%H%M')-changes-manual"
            local path_home_tmp="$tmpUblinuxChng/$(date '+%Y%m%d-%H%M')-home"
            local path_tmp_all="$tmpUblinuxChng/$(date '+%Y%m%d-%H%M')-changes-all"
            [ ! -d "$path_tmp" ] && install -m 655 -d "$path_tmp"
            [ ! -d "$path_home_tmp" ] && install -m 655 -d "$path_home_tmp"
            for user in ${chsUsers[@]}; do
                [ ! -d "$path_home_user_tmp" ] && install -m 655 -d "$tmpUblinuxChng/$(date '+%Y%m%d-%H%M')-home-$user"
            done
            [ ! -d "$path_tmp_all" ] && install -m 655 -d "$path_tmp_all"

            if [ -n "${arg_cups}" ]; then
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$cupsPath" "${path_tmp}" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$printcupPath" "${path_tmp}" &>/dev/null
            fi

            if [ -n "${arg_cpro}" ]; then
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$crpoPath" "${path_tmp}" &>/dev/null
            fi

            if [ -n "${args_nmctl}" ]; then
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$mnctlPath" "${path_tmp}" &>/dev/null
            fi

            if [ -n "${arg_smb}" ]; then
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$varSmbPath" "${path_tmp}" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcSmbPath" "${path_tmp}" &>/dev/null
            fi

            if [ -n "${arg_psswd}" ]; then
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcPasswdPath" "${path_tmp}" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcShadowPath" "${path_tmp}" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcGroupPath" "${path_tmp}" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$etcGshadowPath" "${path_tmp}" &>/dev/null
                cd ${path} && rsync -aAXruR --exclude-from="$excludeFiles" "$varSmbPath" "${path_tmp}" &>/dev/null
            fi
            if [ -n "${args_home}" ]; then
                #rsync -aAXruR --exclude-from="$excludeFilesHome" "/home" "${path_home_tmp}" &>/dev/null
                #mkubm -w -l $(find $tmpUblinuxChng -maxdepth 1 -mindepth 1 -iname '*home') -o ${arg_modules_path}/$(date '+%Y.%m.%d')-home.ubm &>/dev/null && result_ubm=0 || result_ubm=1
                mkubm -w -l "/home" -o ${arg_modules_path}/$(date '+%Y%m%d-%H%M')-home.ubm --mksqfs -ef "$excludeFilesHome" &>/dev/null &>/dev/null && result_ubm=0 || result_ubm=1
            fi

            if [ -n "${args_home_user}" ]; then
                for user in ${chsUsers[@]}; do
                    #rsync -aAXruR --exclude-from="$excludeFilesHome" "/home/$user" "$tmpUblinuxChng/$(date '+%Y.%m.%d')-home-$user" &>/dev/null
                    #mkubm -w -l $(find $tmpUblinuxChng -maxdepth 1 -mindepth 1 -iname "*home-$user") -o ${arg_modules_path}/$(date '+%Y.%m.%d')-home-$user.ubm &>/dev/null && result_ubm=0 || result_ubm=1
                    mkubm -w -l "/home/$user" -o ${arg_modules_path}/$(date '+%Y%m%d-%H%M')-home-$user.ubm --mksqfs -ef "$excludeFilesHome" &>/dev/null && result_ubm=0 || result_ubm=1
                done
            fi
            if [ -n "${args_all}" ]; then
                #cd "${path}" && rsync -aAXruR --exclude-from="$excludeFiles" * "${path_tmp_all}" #&>/dev/null
                #mkubm -w -l $(find $tmpUblinuxChng -maxdepth 1 -mindepth 1 -iname "*changes") -o ${arg_modules_path}/$(date '+%Y%m%d-%H%M')-changes.ubm &>/dev/null && result_ubm=0 || result_ubm=1
                mkubm -w -l ${path} -o ${arg_modules_path}/$(date '+%Y%m%d-%H%M')-changes-all.ubm --mksqfs -ef "$excludeFiles" && result_ubm=0 || result_ubm=1
            fi
            if [ -n "${arg_cups}" ] || [ -n "${arg_cpro}" ] || [ -n "${args_nmctl}" ] || [ -n "${arg_smb}" ] || [ -n "${arg_psswd}" ]; then
                mkubm -w -l $(find $tmpUblinuxChng -maxdepth 1 -mindepth 1 -iname '*changes-manual') -o ${arg_modules_path}/$(date '+%Y%m%d-%H%M')-changes-manual.ubm &>/dev/null && result_ubm=0 || result_ubm=1
            fi
            rm -rf "${path_tmp}" "${path_home_tmp}" "${path_home_user_tmp}"
            rm -rdf "${tmpUblinuxChng}"
        fi

    elif [ -z "${chk_rghts_md}" ];then
        chk_rghts_md=2
    else
        chk_rghts_md=0
    fi

    if [ "${chk_rghts_rc}" == "0" ] && [ "${chk_rghts_md}" == "0" ]; then
        if [ -n "${arg_gui_yad}" ] || [ -n "${arg_cli}" ]; then
            return 4
        else
            echo "$(i18n "Saving is not possible! Please check your access rights.")"
            return 4
        fi
    fi

    if [ "${chk_rghts_rc}" == "0" ]; then
        if [ -n "${arg_gui_yad}" ] || [ -n "${arg_cli}" ]; then
            return 2
        else
            echo "$(i18n "Saving to the user's changes directory is not possible! Please check your access rights.")"
            return 2
        fi
    fi

    if [ "${chk_rghts_md}" == "0" ]; then
        if [ -n "${arg_gui_yad}" ] || [ -n "${arg_cli}" ]; then
            return 3
        else
            echo "$(i18n "Saving to the user module is not possible! Please check your access rights.")"
            return 3
        fi
    fi

    if ([ -z "${result_cups}" ] || [ "${result_cups}" == "0" ]) && \
        ([ -z "${result_cpro}" ] || [ "${result_cpro}" == "0" ]) && \
        ([ -z "${result_nmctl}" ] || [ "${result_nmctl}" == "0" ]) && \
        ([ -z "${result_home}" ] || [ "${result_home}" == "0" ]) && \
        ([ -z "${result_home_user}" ] || [ "${result_home_user}" == "0" ]) && \
        ([ -z "${result_all}" ] || [ "${result_all}" == "0" ]) && \
        ([ -z "${result_ubm}" ] || [ "${result_ubm}" == "0" ]) && \
        ([ -z "${result_smb}" ] || [ "${result_smb}" == "0" ]) && \
        ([ -z "${result_psswd}" ] || [ "${result_psswd}" == "0" ]); then

        if [ -n "${arg_gui_yad}" ] || [ -n "${arg_cli}" ]; then
            return 0
        else
            echo "$(i18n "Save completed!")"
            return 0
        fi

    else

        if [ -n "${arg_gui_yad}" ] || [ -n "${arg_cli}" ]; then
            return 1
        else
            echo "$(i18n "Save error!")"
            return 1
        fi

    fi
}
export -f main

check_access_save(){
    local memTotalInByte="$(free -b | grep Mem | awk '{print $2}')"
    local accessMem="$(($memTotalInByte-1073741824))"
    local tmpSize="0"
    local currSize="0"
    path=($@)
    for i in ${path[@]}; do
        if [ -d "$i" ] || [ -f "$i" ]; then
            tmpSize="$(du -shb "$i" | awk '{print $1}')"
            currSize="$(($currSize + $tmpSize))"
            tmpSize="0"
        fi
    done
    
    if [ "$currSize" -gt "0" ]; then
        if [ "$currSize" -le "$accessMem" ]; then
            return 0
        else
            return 1
        fi
    else
        return 1
    fi
}
export -f check_access_save

menu_exit(){
    if [ -n "${arg_cli}" ]; then
        menu --backtitle "$(i18n "Managing the saving of changes")" \
                --title "$(i18n "Submit your request")" \
                --defaultno \
                --yesno "$(i18n "Do you really want to quit the program?")" 0 0
        case "$?" in
            $OK_C)
                clear 
                exit
            ;;
        esac
    fi

    rm -f $tmpChooseModule $tmpChooseUsers $chooserUsers $tmpExitCodeMain $excludeFiles $excludeFilesHome

    return
}
export -f menu_exit

main_menu(){
    local arg=""
    if [ -n "${arg_gui_yad}" ]; then

        yad --plug="${fkey}" \
            --tabnum=1 \
            --form \
            --columns=1 \
            --field=$"$(i18n "Save to:")!$(i18n "%s - User's changes directory\\n%s - User module" "/ublinux-data/rootcopy" "/ublinux-data/modules")":cb "/ublinux-data/modules!/ublinux-data/rootcopy" \
            --field=" ":lbl "" \
            --field="$(i18n "Save mode:")":lbl "" \
            --field=$"$(i18n "Installed printers")!$(i18n "Save the settings of the installed printers")":chk "${chk_cups_save}" \
            --field=$"$(i18n "CryptoPro settings")!$(i18n "Save CryptoPro settings")":chk "${chk_cpro_save}" \
            --field=$"$(i18n "Network interface settings")!$(i18n "Save network interface settings")":chk "${chk_nmctl_save}" \
            --field=$"$(i18n "Samba Settings")!$(i18n "Save Samba Settings")":chk "" \
            --field=$"$(i18n "Group and User Settings")!$(i18n "Save group and user settings")":chk "" \
            --field=$"$(i18n "All home folders")!$(i18n "Save changes from all home folders")":chk "" \
            --field=$"$(i18n "Home directories of selected users")!$(i18n "Save changes from the home directories of selected users")":chk "" \
            --field=$"$(i18n "All system changes")!$(i18n "Save all system changes")":chk "" \
            --field=" ":lbl "" \
            --field=$"yad-save:fbtn" "${save_cmd}" &>/dev/null &
    
        yad --plug="${fkey}" \
            --tabnum=2 \
            --form \
            --columns=1 \
            --field=$"$(i18n "Delete changes modules")":fbtn "${del_modul_cmd}" \
            --field=$"$(i18n "Clear saved changes")!$(i18n "Clear the save change directory")":fbtn "${clear_cmd}" \
            --field=$"$(i18n "Clear changes")!$(i18n "Clearing system changes (/ublinux-data/changes)")":fbtn "${clear_changes_cmd}" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" \
            --field=" ":lbl "" &>/dev/null &

        yad --notebook \
            --center \
            --key="${fkey}" \
            --tab="$(i18n "Saving change")" \
            --tab="$(i18n "Settings")" \
            --button="yad-close:0" \
            --height=500 \
            --width=400 \
            --window-icon=ublinux-ubsave \
            --image=ublinux-ubsave \
            --text="$(i18n "Managing the saving of changes")" \
            --title="$(i18n "Saving changes")"

        # yad --title="$(i18n "Saving changes")" \
        #     --center \
        #     --window-icon=ublinux-ubsave \
        #     --image=ublinux-ubsave \
        #     --image-on-top \
        #     --scroll \
        #     --vscroll-policy=auto \
        #     --text="$(i18n "Managing the saving of changes")" \
        #     --form \
        #     --columns=1 \
        #     --field=$"$(i18n "Save to:")!$(i18n "%s - User's changes directory\\n%s - User module" "/ublinux-data/rootcopy" "/ublinux-data/modules")":cb "/ublinux-data/modules!/ublinux-data/rootcopy" \
        #     --field="":lbl "" \
        #     --field="$(i18n "Save mode:")":lbl "" \
        #     --field=$"$(i18n "Installed printers")!$(i18n "Save the settings of the installed printers")":chk "${chk_cups_save}" \
        #     --field=$"$(i18n "CryptoPro settings")!$(i18n "Save CryptoPro settings")":chk "${chk_cpro_save}" \
        #     --field=$"$(i18n "Network interface settings")!$(i18n "Save network interface settings")":chk "${chk_nmctl_save}" \
        #     --field=$"$(i18n "Samba Settings")!$(i18n "Save Samba Settings")":chk "" \
        #     --field=$"$(i18n "Group and User Settings")!$(i18n "Save group and user settings")":chk "" \
        #     --field=$"$(i18n "All home folders")!$(i18n "Save changes from all home folders")":chk "" \
        #     --field=$"$(i18n "Home directories of selected users")!$(i18n "Save changes from the home directories of selected users")":chk "" \
        #     --field=$"$(i18n "All system changes")!$(i18n "Save all system changes")":chk "" \
        #     --field="":lbl "" \
        #     --field="$(i18n "Settings:")":lbl "" \
        #     --field=$"$(i18n "Delete changes modules")":fbtn "${del_modul_cmd}" \
        #     --field=$"$(i18n "Clear saved changes")!$(i18n "Clear the save change directory")":fbtn "${clear_cmd}" \
        #     --field=$"$(i18n "Clear changes")!$(i18n "Clearing system changes (/ublinux-data/changes)")":fbtn "${clear_changes_cmd}" \
        #     --field="":lbl "" \
        #     --field=$"yad-save:fbtn" "${save_cmd}" \
        #     --no-escape \
        #     --no-buttons \
        #     --height=695 \
        #     --width=400
    fi

    if [ -n "${arg_cli}" ]; then
        answere=$(menu --backtitle "$(i18n "Managing the saving of changes")" \
                             --title "$(i18n "Main menu")" \
                             --cancel-label "$(i18n "Exit")" \
                             --default-item 1 \
                             --clear \
                             --no-collapse \
                             --tab-correct \
                             --menu "$(i18n "Please make a choice:")" 0 0 0 \
                             1 "$(i18n "Saving change")" \
                             2 "$(i18n "Settings")")

        return_value="$?"
        case "$return_value" in
            "$OK_C")
                case "${answere}" in
                    1)
                        while true; do menu_choose_save && break; done
                    ;;
                    2)
                        while true; do menu_settings && break; done
                    ;;
                esac
            ;;
            "$CANCEL_C") menu_exit;;
            "$ESC_C") menu_exit;;
        esac
        return 1
    fi
}
export -f main_menu

menu_choose_save(){
    answere=$(menu --backtitle "$(i18n "Managing the saving of changes")" \
                         --title "$(i18n "Saving change")" \
                         --cancel-label "$(i18n "Back")" \
                         --default-item 1 \
                         --clear \
                         --no-collapse \
                         --tab-correct \
                         --menu "$(i18n "Please make a choice:")" 0 0 0 \
                         1 "$(i18n "Save the settings of the installed printers")" \
                         2 "$(i18n "Save CryptoPro settings")" \
                         3 "$(i18n "Save network interface settings")" \
                         4 "$(i18n "Save Samba Settings")" \
                         5 "$(i18n "Save group and user settings")" \
                         6 "$(i18n "Save changes from all home folders")" \
                         7 "$(i18n "Save changes from the home directories of selected users")" \
                         8 "$(i18n "Save all system changes")")

    return_value="$?"
    case "$return_value" in
        "$OK_C")
            case "${answere}" in
                1)
                    while true; do dir_select_cli 0 && break; done
                ;;
                2)
                    while true; do dir_select_cli 1 && break; done
                ;;
                3)
                    while true; do dir_select_cli 2 && break; done
                ;;
                4)
                    while true; do dir_select_cli 3 && break; done
                ;;
                5)
                    while true; do dir_select_cli 4 && break; done
                ;;
                6)
                    while true; do dir_select_cli 5 && break; done
                ;;
                7)
                    while true; do choose_user && break; done
                ;;
                8)
                    while true; do dir_select_cli 6 && break; done
                ;;
            esac
        ;;
        "$CANCEL_C") return 0;;
        "$ESC_C") return 0;;
    esac

    return 1
}
export -f menu_choose_save

menu_settings(){
    answere=$(menu --backtitle "$(i18n "Managing the saving of changes")" \
                         --title "$(i18n "Settings")" \
                         --cancel-label "$(i18n "Back")" \
                         --default-item 1 \
                         --clear \
                         --no-collapse \
                         --tab-correct \
                         --menu "$(i18n "Please make a choice:")" 0 0 0 \
                         1 "$(i18n "Delete changes modules")" \
                         2 "$(i18n "Clear saved changes")" \
                         3 "$(i18n "Clear changes")")
#"
    return_value="$?"
    case "$return_value" in
        "$OK_C")
            case "${answere}" in
                1)
                    while true; do run_del_modul && break; done
                ;;
                2)
                    while true; do run_clear "save" && break; done
                ;;
                3)
                    while true; do run_clear "sys" && break; done
                ;;
            esac
        ;;
        "$CANCEL_C") return 0;;
        "$ESC_C") return 0;;
    esac

    return 1
}
export -f menu_settings

dir_select_cli(){
    [[ "$1" == "0" ]] && args="-cups "
    [[ "$1" == "1" ]] && args="-cpro "
    [[ "$1" == "2" ]] && args="-nmctl "
    [[ "$1" == "3" ]] && args="-smb "
    [[ "$1" == "4" ]] && args="-psswd "
    [[ "$1" == "5" ]] && args="-home "
    [[ "$1" == "6" ]] && args="-all "
    [[ "$1" == "7" ]] && args="-home-user "

    local lines_count=$(tput lines)
    local cols_count=$(tput cols)
    local widg_hight=$(( $lines_count - 9 ))
    local widg_wight=$(( $cols_count - 9 ))
    local method=$(menu --backtitle "$(i18n "Managing the saving of changes")" \
                        --title "$(i18n "Select a save location")" \
                        --cancel-label "$(i18n "Back")" \
                        --default-item 1 \
                        --clear \
                        --no-collapse \
                        --tab-correct \
                        --menu "$(i18n "Please make a choice:")" 0 0 0 \
                            1 "$(i18n "Save to the user's changes directory (/ublinux-data/rootcopy)")" \
                            2 "$(i18n "Save in the user module (/ublinux-data/modules)")")
#"
    return_value="$?"
    case "$return_value" in
        "$OK_C")
            case "${method}" in
                1)
                    args="-rc ${args}"
                    run_save "${args}"
                ;;
                2)
                    args="-modules ${args}"
                    run_save "${args}"
                ;;
            esac
        ;;
        "$CANCEL_C") return 0;;
        "$ESC_C") return 0;;
    esac
    return 0
}

[[ -z $1 ]] && set - "-cli"
while [[ -n $1 ]]; do
    case $1 in
        -gui)
            export arg_gui_yad="-gui"
        ;;
        -cli)
            export arg_cli="-cli"
        ;;
        -h | --help)
            export arg_help="-h"
        ;;
        *)
            export args_all_keys+="$1 "
        ;;
    esac
	shift
done

[[ -n "${arg_help}" ]] && echo -e "$(i18n "${msg_version}" "${VERSION_SCRIPT}")" && echo -e "$(i18n "${msg_help}" "$(basename $0)")\n" && exit 0
#"
[[ -n "${arg_cli}" ]] && while true; do main_menu && break; done
[[ -n "${arg_gui_yad}" ]] && main_menu && exit 0
[[ -z "${arg_cli}" ]] && [[ -z "${arg_gui_yad}" ]] && main $args_all_keys && exit 0


exit 1
