#!/bin/bash
# version: 1.5.2, date: 26.03.2025 12:08
set -e

MAKE_OFFLINE="false"
UTILS_INSTALLED="false"
DOTNET_INSTALLED="false"
PAGESCLIENTID_="0"
PAGESCLIENTSECRET_="0"

function install_offline {
    if [ $distr = rpm ]; then
	if [ $MAKE_OFFLINE = "true" ]; then
	    umount "${CDDISK_DIR}/dnfcache" || true
	    rm -rf "${CDDISK_DIR}/dnfcache" || true
	    mkdir -p "${CDDISK_DIR}/dnfcache" || true
	    mount -o loop "${CDDISK_DIR}/dnfcache.iso" "${CDDISK_DIR}/dnfcache"
	    cat > /etc/yum.repos.d/dnfcache.repo <<END
[r7-office]
name=dnfcache repo
baseurl=file://${CDDISK_DIR}/dnfcache
gpgcheck=0
enabled=1
END
	    extisocount=$(ls ./distr/*.iso 2>/dev/null | wc -l)
	    extisoname=$(find distr/ -name "*.iso" | awk 'NR == 1')
	    echo "extisocount=$extisocount"
	    echo "extisoname=$extisoname"
	    if [ $extisocount \> 0 ]; then
		echo "Full offline installation from iso: $extisoname"
		umount "${PWD}/dnfcachedisk" || true
		rm -rf "${PWD}/dnfcachedisk" || true
		mkdir -p "${PWD}/dnfcachedisk" || true
		mount -o loop "${PWD}/$extisoname" "${PWD}/dnfcachedisk"
		cp ${PWD}/dnfcachedisk/media.repo /etc/yum.repos.d/dnfcachedisk.repo
		echo "baseurl=file:///${PWD}/dnfcachedisk" >> /etc/yum.repos.d/dnfcachedisk.repo
		echo "enabled=1" >> /etc/yum.repos.d/dnfcachedisk.repo
	    fi
	    dnf makecache
	    #dnf update -y --skip-broken --nobest --allowerasing
	    dnf install unzip util-linux coreutils jq rsyslog -y
	fi
    elif [ $distr = deb ]; then
	if [ $MAKE_OFFLINE = "true" ]; then
	    #umount ${CDDISK_DIR}/iso || true
	    rm -rf ${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/iso || true
	    mkdir -p ${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/iso || true
	    mount -o loop "${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/astralinux_1.7.4.iso" ${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/iso
	    echo "deb [trusted=yes] file://${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/iso/archives ./" >/etc/apt/sources.list.d/02-archives.list
	    apt update
	fi
    elif [ $distr = alt ]; then
	if [ $MAKE_OFFLINE = "true" ]; then
	    #umount ${CDDISK_DIR}/iso
	    mkdir -p ${CDDISK_DIR}/iso
	    mount -o loop "${CDDISK_DIR}/altlinux.iso" ${CDDISK_DIR}/iso
	    apt-repo add "rpm file:${CDDISK_DIR}/iso x86_64 r7"
	    apt-repo add "rpm file:${CDDISK_DIR}/iso noarch r7"
	    apt-get update
	fi
    fi
}

function uninstall_offline {
    if [ $distr = rpm ]; then
	if [ $MAKE_OFFLINE = "true" ]; then
	    umount "${CDDISK_DIR}/dnfcache" || true
	    rm -rf "${CDDISK_DIR}/dnfcache" || true
	    rm -f /etc/yum.repos.d/dnfcache.repo
	    extisocount=$(ls ./distr/*.iso 2>/dev/null | wc -l)
	    echo "extisocount=$extisocount"
	    if [ $extisocount \> 0 ]; then
		echo "Full offline finish installation"
		umount "${PWD}/dnfcachedisk" || true
		rm -rf "${PWD}/dnfcachedisk" || true
		rm -rf /etc/yum.repos.d/dnfcachedisk.repo
	    fi
	    sudo dnf clean all
	fi
    elif [ $distr = deb ]; then
	if [ $MAKE_OFFLINE = "true" ]; then
	    umount ${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/iso
	    rm -rf ${CDDISK_DIR}/CDDiskPack/CDinstall_Astra_1.7.4/iso || true
	    rm -f /etc/apt/sources.list.d/02-archives.list
	    apt update
	fi
    elif [ $distr = alt ]; then
	if [ $MAKE_OFFLINE = "true" ]; then
	    umount ${CDDISK_DIR}/iso
	    rm -rf ${CDDISK_DIR}/iso
	    mount -o loop "${CDDISK_DIR}/altlinux.iso" ${CDDISK_DIR}/iso
	    apt-repo rm "rpm file:${CDDISK_DIR}/iso x86_64 r7"
	    apt-repo rm "rpm file:${CDDISK_DIR}/iso noarch r7"
	    apt-get update
	fi
    fi
}

function update_dotnet {
    echo ""
    echo ""
    echo "###########################################"
    echo "########## Проверка версии dotnet #########"
    echo "###########################################"
    echo ""
    echo ""
    if [ $distr = rpm ]; then
        if rpm --quiet -q --whatprovides dotnet-sdk-6.0; then
            echo ""
            echo ""
            echo "###########################################"
            echo "######### Обновление не требуется #########"
            echo "###########################################"
            echo ""
            echo ""
        else
            echo ""
            echo ""
            echo "###########################################"
            echo "####### Процесс обновления dotnet #########"
            echo "###########################################"
            echo ""
            echo ""
            dnf install dotnet-sdk-6.0 aspnetcore-runtime-6.0 -y 1>> /dev/null
        fi
    elif [ $distr = deb ]; then
        if dpkg -l | grep -q "dotnet-sdk-6.0"; then
            echo ""
            echo ""
            echo "###########################################"
            echo "######### Обновление не требуется #########"
            echo "###########################################"
            echo ""
            echo ""
        else
            echo ""
            echo ""
            echo "###########################################"
            echo "####### Процесс обновления dotnet #########"
            echo "###########################################"
            echo ""
            echo ""
            apt update 1>> /dev/null
	    apt install -y dotnet-sdk-6.0 aspnetcore-runtime-6.0 1>> /dev/null
        fi
    fi
}
function unzip_install {

    echo ""
    echo ""
    echo "##################################################"
    echo "### Проверка установленного дополнительного ПО ###"
    echo "##################################################"
    echo ""
    echo ""

    if [ $distr = deb ]; then
        if [ $this_astra -eq 1 ]; then
            echo ""
            echo ""
            echo "###########################################"
            echo "## Установка unzip bsdutils coreutils jq ##"
            echo "###########################################"
            echo ""
            echo ""
            apt update 1>> /dev/null
	    apt install unzip bsdutils coreutils jq -y 1>> /dev/null
        else
            echo ""
            echo ""
            echo "###################################################"
            echo "## Установка unzip bsdutils coreutils jq rsyslog ##"
            echo "###################################################"
            echo ""
            echo ""
            apt update 1>> /dev/null
	    apt install unzip bsdutils coreutils jq rsyslog -y 1>> /dev/null 
        fi
    elif [ $distr = rpm ]; then
        echo ""
        echo ""
        echo "#####################################################"
        echo "## Установка unzip util-linux coreutils jq rsyslog ##"
        echo "#####################################################"
        echo ""
        echo ""
        dnf install unzip util-linux coreutils jq rsyslog -y || :
    elif [ $distr = alt ]; then
        echo ""
        echo ""
        echo "#####################################################"
        echo "## Установка unzip coreutils jq                    ##"
        echo "#####################################################"
        echo ""
        echo ""
        apt-get install unzip coreutils jq -y 1>> /dev/null
    fi
    echo ""
    echo ""
    echo "########"
    echo "## Ok ##"
    echo "########"
    echo ""
    echo ""  
}

function log_write {

exec > >(tee >(logger  -p local0.notice -t `basename "$0"`))
exec 2> >(tee >&2 >(logger  -p local0.error -t `basename "$0"`))

}
function init_os {

    echo ""
    echo ""
    echo "##########################"
    echo "#### Инициализация ОС ####"
    echo "##########################"
    echo ""
    echo ""

    if dpkg --help &>> /dev/null; then
        distr=deb
        this_astra=0
        log_file=/var/log/syslog
        if [ -e /etc/astra_version ]; then
            this_astra=1
            log_file=/var/log/syslog
        fi
    elif rpm --help &>> /dev/null; then
        log_file=/var/log/messages
        if apt-get --help &>> /dev/null; then
            distr=alt
        else
            distr=rpm
            if [[ "$(cat /etc/redhat-release)" == *"Stream"* ]]; then
                redhat_ver=centos
            elif [[ "$(cat /etc/redhat-release)" == *"MUROM"* ]]; then
                redhat_ver=redos
            fi
        fi
    fi

    echo $distr $this_astra $redhat_ver
    echo ""
    echo ""
    echo "################################"
    echo "############## Ok ##############"
    echo "################################"
    echo ""
    echo ""

}

function check_installed {

    if [ $UTILS_INSTALLED!="true" ]; then
	# Установим unzip
	unzip_install
	UTILS_INSTALLED="true"
    fi

    if [ $DOTNET_INSTALLED!="true" ]; then
	# Обновление dotnet
	update_dotnet
	DOTNET_INSTALLED="true"
    fi
}

function update_url {
set +e
    if [ "$#" -eq 2 ]; then
        if [ $1 != "" ]; then
            sed -i "s/cddisk.r7-office.ru/$DOMAIN_NAME/g" $1
            echo "Update url Ok"
        else
            echo "Not update url in ${1}" 
        fi
        if [ $2 != "" ]; then
            sed -i "s/cddisk.r7-office.ru/$DOMAIN_NAME/g" $2
            echo "Update url Ok"
        else
            echo "Not update url in ${2}" 
        fi
    else
        echo "No parameters to update url" 
    fi
set -e
}

function init_url {

    if [ "$#" -eq 2 ]; then
        if [ $1 != "" ]; then
            echo "Init url Ok"
        else
            echo "no valid url in cddisk ${1}"
        fi

        if [ $2 != "" ]; then
            echo "Init url Ok"
        else
            echo "no valid url in cddisk ${2}"
        fi
    else
        echo "No parameters to init url" 
    fi

}

function check_pages_forms_installed {
    PAGES_CONFIG_FILENAME=/opt/r7-office/java-maker/external.properties
    if [ -f $PAGES_CONFIG_FILENAME ]; then
	PAGESCLIENTID_=$(grep -oP "spring.security.oauth2.client.registration.custom-client.client-id=[^\";]*" $PAGES_CONFIG_FILENAME | head -1 | cut -d'=' -f2);
	echo "PAGESCLIENTID_=$PAGESCLIENTID_"
	PAGESCLIENTSECRET_=$(grep -oP "spring.security.oauth2.client.registration.custom-client.client-secret=[^\";]*" $PAGES_CONFIG_FILENAME | head -1 | cut -d'=' -f2);
	echo "PAGESCLIENTSECRET_=$PAGESCLIENTSECRET_"
	if [ -f /opt/r7-office/pagesforms.update ]; then
	    rm /opt/r7-office/pagesforms.update
	fi
    fi
}
function update_db_pages_forms {
    SQL_FILE="$PATCH_DIR/Patch/Db/Alter/One_time_2024_s_09/patch-2025_04_28-InitOAuthApplications.sql"
    if [ -f /opt/r7-office/pagesforms.update ]; then
    PAGESFORMS_FILENAME=/opt/r7-office/pagesforms.update
    PAGES_URL=$(grep -oP ":pages_url=[^\";]*" $PAGESFORMS_FILENAME | head -1 | cut -d'=' -f2);
    FORMS_URL=$(grep -oP ":forms_url=[^\";]*" $PAGESFORMS_FILENAME | head -1 | cut -d'=' -f2);
    PAGES_CLIENT_ID=$(grep -oP ":pages_client_id=[^\";]*" $PAGESFORMS_FILENAME | head -1 | cut -d'=' -f2);
    PAGES_SECRET=$(grep -oP ":pages_secret=[^\";]*" $PAGESFORMS_FILENAME | head -1 | cut -d'=' -f2);
    FORMS_CLIENT_ID=$(grep -oP ":forms_client_id=[^\";]*" $PAGESFORMS_FILENAME | head -1 | cut -d'=' -f2);
    FORMS_SECRET=$(grep -oP ":forms_secret=[^\";]*" $PAGESFORMS_FILENAME | head -1 | cut -d'=' -f2);
    echo "PAGES_URL=$PAGES_URL"
    echo "FORMS_URL=$FORMS_URL"
    echo "PAGES_CLIENT_ID=$PAGES_CLIENT_ID"
    echo "PAGES_SECRET=$PAGES_SECRET"
    echo "FORMS_CLIENT_ID=$FORMS_CLIENT_ID"
    echo "FORMS_SECRET=$FORMS_SECRET"
    if [ -f $SQL_FILE ]; then
        echo "Edit sql file $SQL_FILE"
        sed -i "s#:pages_url#'$PAGES_URL'#g" $SQL_FILE
        sed -i "s#:forms_url#'$FORMS_URL'#g" $SQL_FILE
        sed -i "s#:pages_client_id#'$PAGES_CLIENT_ID'#g" $SQL_FILE
        sed -i "s#:pages_secret#'$PAGES_SECRET'#g" $SQL_FILE
        sed -i "s#:forms_client_id#'$FORMS_CLIENT_ID'#g" $SQL_FILE
        sed -i "s#:forms_secret#'$FORMS_SECRET'#g" $SQL_FILE
    else
        echo "Not found sql file $SQL_FILE"
    fi
    else
	SQL_FILE_RENAMED="$PATCH_DIR/Patch/Db/Alter/One_time_2024_s_09/patch-2025_04_28-InitOAuthApplications.off"
	mv $SQL_FILE $SQL_FILE_RENAMED
    fi
}

function update_database {
    
    if [ "$#" -eq 1 ]; then
        PATCH_FILE=$1
        unzip "$PATCH_FILE" -d $PATCH_DIR
    fi

    update_db_pages_forms

    # Данные для авторизации в PostgreSQL
    DB_PATH_PARAM=/opt/r7-office/Api/appsettings.json
    PSQL_HOST=$(grep -oP "Host=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_DB_NAME=$(grep -oP "Database=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_USER=$(grep -oP "Username=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PASS=$(grep -oP "Password=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PORT=$(grep -oP "Port=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    
    export PGPASSWORD=$PSQL_PASS
    PSQL="psql -b -h$PSQL_HOST -p$PSQL_PORT -d$PSQL_DB_NAME -U$PSQL_USER"
    echo "DB_HOST=$PSQL_HOST"
    echo "DB_PORT=$PSQL_PORT"
    echo "DB_NAME=$PSQL_DB_NAME"
    echo "DB_USER=$PSQL_USER"
    echo "PSQL=$PSQL"

    connect_db

    echo ""
    echo ""
    echo "################################"
    echo "#### Обновление БД бэкенда #####"
    echo "################################"
    echo ""
    echo ""

    for SQLFILE in $(find $PATCH_DIR/Patch/Db/ -name "*.sql" | sort -n)
    do
        echo ""
        TEMPSQL="$PSQL -f\"$SQLFILE\""
        echo "RUN $TEMPSQL"
        $PSQL -f "$SQLFILE"
        echo ""
    done

    echo ""
    echo ""
    echo "#################################"
    echo "############## END ##############"
    echo "## Версия БД после обновления: ##"
    echo "#################################"
    echo ""
    echo ""

    $PSQL -c 'SELECT * FROM public."Versions";'
    export PGPASSWORD=" "

    echo ""
    echo ""
    echo "################################"
    echo "### Обновление БД завершено ####"
    echo "################################"
    echo ""
    echo ""
}

function connect_db {

    $PSQL -c ";" 1>>/dev/null
    ERRCODE=$?

    if [ $ERRCODE -ne 0 ]; then
        service postgresql start 1>>/dev/null
        $PSQL -c ";" 1>>/dev/null || \
        { echo "ERROR: can't connect to postgressql database"; exit 1; }
    fi

    $PSQL -c ";"
    ERRCODE=$?

    if [ $ERRCODE -ne 0 ]; then
        echo ""
        echo "ERROR: can't connect to postgressql database";.
        exit 1;
    fi

}
function update_backend {

    # Проверка наличия аргумента

    if [ "$#" -ne 1 ]; then
        echo ""
        echo "Использование для обновления бэкенда: $0 -b <путь_к_патчу.zip>"
        exit 1
    fi

    # Данные путей к патчу
    PATCH_FILE=$1
    
    # Распаковываем
    echo ""
    echo "##########################################"
    echo "########### Распаковка бэкенда ###########"
    echo "##########################################"
    echo ""
    echo ""

    unzip "$PATCH_FILE" -d $PATCH_DIR

    echo ""
    echo ""
    echo "#################################"
    echo "## Распаковка бэкенд завершена ##"
    echo "#################################"
    echo ""
    echo ""

    # Останавливаем сервисы

    echo ""
    echo ""
    echo "###################################"
    echo "## Останавливаем сервисы бэкенда ##"
    echo "###################################"
    echo ""
    echo ""

    supervisorctl stop all

    # Обновление БД
    echo ""
    echo ""
    yes_or_no "##### Обновлять Базу данных?"
    echo ""
    echo ""
    if [ $answer -eq 0 ]; then
        update_database
    else
        echo ""
        echo ""
        echo "#################################"
        echo "### Не выбрано обновление БД ####"
        echo "#################################"
        echo ""
        echo ""
    fi

    # Делаем бекап
    echo ""
    echo ""
    echo "#################################"
    echo "#### Бекапирование бэкенда ######"
    echo "#################################"
    echo ""
    echo ""
    for backend in Api FileStorage SearchApi Service.Registry Sso.Api Processing
    do
        echo ""
        echo $backend
        cp -vpr $PATH_BACKEND/$backend "$PATH_BACKEND/$backend-$DATE_SUFFIX"
        if ls $PATH_BACKEND/$backend-$DATE_SUFFIX ; then 
            echo ""
            echo "############################################################################"
            echo ""
            echo "Копия ${PATH_BACKEND}/${backend}-${DATE_SUFFIX} создана"
            echo ""
            echo "############################################################################"
            echo ""
        else
            echo ""
            echo "########################################"
            echo ""
            echo "Копии ${backend} не существует"
            echo ""
            echo "########################################"
            echo ""
        fi
    done

    # Обновляем бэкенд
    echo ""
    echo ""
    echo "#################################"
    echo "###### Обновление бэкенда #######"
    echo "#################################"
    echo ""
    echo ""
    COUNT_BACK=$(ls -la $PATCH_DIR/Patch | wc -l)
    if [ $COUNT_BACK -gt 7 ]; then
        for backend in Api Sso.Api Processing FileStorage SearchApi Service.Registry
        do
            echo ""
            echo "#################################"
            echo ""
            echo $backend
            echo ""
            echo "#################################"
            echo ""
            cp -vpr "$PATCH_DIR/Patch/$backend/"* $PATH_BACKEND/$backend
            chown cddisk:cddisk -R $PATH_BACKEND/$backend
            echo ""
            echo "#################################"
            echo ""
            echo "${backend}: Ok"
            echo ""
            echo "#################################"
            echo ""
        done
        echo ""
        echo ""
        yes_or_no "######## Обновлять веб?"
        echo ""
        echo ""
        if [ $answer -eq 0 ]; then
            update_all_web
        else
            echo ""
            echo ""
            echo "#################################"
            echo "## Не выбрано обновление веб ####"
            echo "#################################"
            echo ""
            echo ""
        fi

    else
        for backend in Api Sso.Api Processing
        do
            echo ""
            echo "#################################"
            echo ""
            echo $backend
            echo ""
            echo "#################################"
            echo ""
            cp -vpr "$PATCH_DIR/Patch/$backend/"* $PATH_BACKEND/$backend
            chown cddisk:cddisk -R $PATH_BACKEND/$backend
            echo ""
            echo "#################################"
            echo ""
            echo "${backend}: Ok"
            echo ""
            echo "#################################"
            echo ""
        done
    fi

    # Запустить сервисы
    echo ""
    echo ""
    echo "#################################"
    echo "####### Запуск сервисов #########"
    echo "#################################"
    echo ""
    echo ""

    supervisorctl start all

    for backend in api filestorage searchapi registry apisso processing
    do
        status_back=$(supervisorctl status $NAME_DISTR:$backend | grep RUNNING | wc -l)
        if [ $status_back -eq 1 ] ; then
            echo ""
            echo "#####################################"
            echo ""
            echo "Сервис ${backend} запущен"
            echo ""
            echo "#####################################"
            echo ""
        else
            echo ""
            echo "#####################################"
            echo ""
            echo "Ошибка запуска ${backend}"
            echo ""
            echo "#####################################"
            echo ""
        fi
    done

    sleep 5
    version_back=$(curl http://localhost:38033/api/v1/version 2>/dev/null | jq .Version)
    echo ""
    echo ""
    echo "#################################"
    echo "## Версия Api:${version_back} ###"
    echo "#################################"
    echo ""
    echo ""
}

function update_all_web {
    echo ""
    echo ""
    echo "#################################"
    echo "#### Обновление Web из Патча ####"
    echo "#################################"
    echo ""
    echo ""

    LIST_WEB=$(ls $PATCH_DIR/Patch/web/)
    PATH_WEB=/var/www/r7-office

    for web in $LIST_WEB
    do
        check_file=$(ls $PATCH_DIR/Patch/web/$web | wc -l)
        if [[ $check_file -gt 1 && -d "${PATH_WEB}/${web}" ]]; then
            echo ""
            echo "#####################################"
            echo ""
            echo "Начало обновления ${web}"
            echo ""
            echo "#####################################"
            echo ""

            mv -v $PATH_WEB/$web $PATH_WEB/$web-$DATE_SUFFIX

            echo ""
            echo "#####################################################################################"
            echo ""
            echo "Бекап старых файлов ${web} по пути ${PATH_WEB}/${web}-${DATE_SUFFIX}"
            echo ""
            echo "#####################################################################################"
            echo ""

            cp -vr $PATCH_DIR/Patch/web/$web $PATH_WEB/$web
            chmod 755 $PATH_WEB/$web -R

            if [ -d $PATH_WEB/$web ]; then
                echo ""
                echo "#############################################"
                echo ""
                echo "Обновление ${web} завершено успешно"
                echo ""
                echo "#############################################"
                echo ""
            else
                echo ""
                echo "#########################################"
                echo ""
                echo "Обновление ${web} не состоялось"
                echo ""
                echo "#########################################"
                echo ""

                echo ""
                echo ""
                echo "#####################################"
                echo "##### Восстановление из бекапа ######"
                echo "#####################################"
                echo ""

                mv -v $PATH_WEB/$web-$DATE_SUFFIX $PATH_WEB/$web
                if [ -d "${PATH_WEB}/${web}" ]; then
                    echo ""
                    echo "############################################################"
                    echo ""
                    echo "Восстановление ${web} прошло успешно"
                    echo ""
                    echo "############################################################"
                    echo ""
                fi
            fi
        else 
            if [ $check_file -lt 1 ]; then
                echo ""
                echo "#########################################"
                echo ""
                echo "${web} недостаёт файлов в патче"
                echo ""
                echo "#########################################"
                echo ""
            elif [ -d "${PATH_WEB}/${web}" ]; then
                echo ""
                echo "###############################################################################################"
                echo "" 
                echo "Данного модуля ${web} нет по стандартному пути ${PATH_WEB}/${web}"
                echo ""
                echo "###############################################################################################"
                echo ""
            fi
        fi
    done
}
function update_web {

    # Проверка наличия аргумента
    if [ "$#" -ne 2 ]; then
        echo ""
        echo "######################################################################################"
        echo ""
        echo "Использование для обновления фронта: $0 -w <имя_фронта> <путь_к_архиву.zip>"
        echo ""
        echo "######################################################################################"
        echo ""
        exit 1
    fi

    PATH_FRONT_FILE=$2
    NAME_FRONT=$1

    echo ""
    echo "#################################"
    echo ""
    echo "Обновление ${NAME_FRONT}"
    echo ""
    echo "#################################"
    echo ""

    FRONT_INIT_DIR=$(grep root /etc/nginx/ -Rl | grep $NAME_FRONT | head -1)
    if [ "$FRONT_INIT_DIR" != "" ]; then
        echo ""
        echo "############################################################"
        echo ""
        echo "Конфигурационный файл ${NAME_FRONT}: ${FRONT_INIT_DIR}"
        echo ""
        echo "############################################################"
        echo ""
        FRONT_DIR=$(cat $FRONT_INIT_DIR | grep root | head -1 | awk '{print $2}' | cut -d ';' -f1)
        if [ "$FRONT_DIR" != "" ]; then
            echo ""
            echo "######################################################################################################"
            echo ""
            echo "Путь до файлов сайта ${NAME_FRONT}: ${FRONT_DIR}"
            echo ""
            echo "######################################################################################################"
            echo ""

            echo ""
            echo "###########################################################################################"
            echo ""
            echo "Бекап старых файлов ${FRONT_DIR} по пути ${FRONT_DIR}-${DATE_SUFFIX}"
            echo ""
            echo "###########################################################################################"
            echo ""

            mv -v $FRONT_DIR $FRONT_DIR-$DATE_SUFFIX

            echo ""
            echo "#########################################################################"
            echo ""
            echo "Распаковка ${PATH_FRONT_FILE} по пути ${FRONT_DIR}"
            echo ""
            echo "#########################################################################"
            echo ""

            unzip $PATH_FRONT_FILE -d $FRONT_DIR
            chmod 755 -R $FRONT_DIR

            echo ""
            echo "########################################"
            echo ""
            echo "Обновление ${NAME_FRONT} завершено"
            echo ""
            echo "########################################"
            echo ""
        else
            echo ""
            echo "########################################"
            echo ""
            echo "Нет директории сайта ${NAME_FRONT}"
            echo ""
            echo "########################################"
            echo ""

            echo ""
            echo "######################################################################################"
            echo ""
            echo "Распаковка произойдёт в стандартную директорию: /var/www/r7-office/${NAME_FRONT}"
            echo ""
            echo "######################################################################################"
            echo ""

            unzip $PATH_FRONT_FILE -d /var/www/r7-office/$NAME_FRONT
            chmod 755 -R /var/www/r7-office/$NAME_FRONT

            echo ""
            echo ""
            echo "##########################################################"
            echo "## Если нужна помощь, обратитесть: support@r7-office.ru ##"
            echo "##########################################################"
            echo ""
            echo ""

            exit 1
        fi
    else
        echo ""
        echo ""
        echo "#################################################################################################"
        echo "## Нет конфигурационного файла ${NAME_FRONT} для Nginx                                        ###"
        echo "## Необходимо его создать вручную, например, в директории /etc/nginx/conf.d/${NAME_FRONT}.conf ##"
        echo "## За пример можете взять любой файл уже установленного модуля, например, Р7-Календарь        ###"
        echo "#################################################################################################"
        echo ""
        echo "##########################################################"
        echo "## Если нужна помощь, обратитесть: support@r7-office.ru ##"
        echo "##########################################################"

        exit 1
    fi

}

function update_single {

    # Проверка наличия аргумента
    if [ "$#" -ne 2 ]; then
        echo ""
        echo "#########################################################################################"
        echo ""
        echo "Использование для обновления фронта: $0 -s <имя_бэкенда> <путь_к_архиву.zip>"
        echo ""
        echo "#########################################################################################"
        echo ""

        exit 1
    fi

    # Данные путей к патчу
    NAME_BACKEND=$1
    PATCH_FILE=$2

    # Распаковка архива
    unzip "$PATCH_FILE" -d $PATCH_DIR

    if [ "$NAME_BACKEND" = "fs" ]; then
        NAME_DIR=FileStorage
        NAME_SERVICE=filestorage
        update_back_single
    elif [ "$NAME_BACKEND" = "sr" ]; then
        NAME_DIR=Service.Registry
        NAME_SERVICE=registry
        update_back_single
    elif [ "$NAME_BACKEND" = "sso" ]; then
        NAME_DIR=Sso.Api
        NAME_SERVICE=apisso
        update_back_single
    elif [ "$NAME_BACKEND" = "api" ]; then
        NAME_DIR=Api
        NAME_SERVICE=api
        update_back_single
    elif [ "$NAME_BACKEND" = "processing" ]; then
        NAME_DIR=Processing
        NAME_SERVICE=processing
        update_back_single
    elif [ "$NAME_BACKEND" = "search" ]; then
        NAME_DIR=SearchApi
        NAME_SERVICE=searchapi
        update_back_single
    fi

    del_tmp

}

function update_back_single {

    if [ -d $PATH_BACKEND/$NAME_DIR ]; then 

        supervisorctl stop $NAME_DISTR:$NAME_SERVICE

        if [[ "$NAME_BACKEND" = "fs" || "$NAME_BACKEND" = "sr" || "$NAME_BACKEND" = "search" ]]; then
            echo ""
            echo "#######################################################"
            echo ""
            echo "Бэкапирование ${NAME_BACKEND}"
            echo ""
            echo "#######################################################"
            echo ""
            cp -vpr $PATH_BACKEND/$NAME_DIR "$PATH_BACKEND/$NAME_DIR-$DATE_SUFFIX"
            if ls $PATH_BACKEND/$NAME_DIR-$DATE_SUFFIX ; then
                echo ""
                echo "###########################################################################"
                echo ""
                echo "Копия ${PATH_BACKEND}/${NAME_DIR}-${DATE_SUFFIX} создана"
                echo ""
                echo "###########################################################################"
                echo ""
            else
                echo ""
                echo "#########################################"
                echo ""
                echo "Копии ${NAME_DIR} не существует"
                echo ""
                echo "#########################################"
                echo ""
            fi
            echo ""
            echo "#################################################"
            echo ""
            echo "Обновление ${NAME_BACKEND}"
            echo ""
            echo "#################################################"
            echo ""

            cp -vpr "$PATCH_DIR/"* $PATH_BACKEND/$NAME_DIR
            chown cddisk:cddisk -R $PATH_BACKEND/$NAME_DIR
        else
            echo ""
            echo "###################################################"
            echo ""
            echo "Бэкапирование ${NAME_BACKEND}"
            echo ""
            echo "###################################################"
            echo ""
            cp -vpr $PATH_BACKEND/$NAME_DIR "$PATH_BACKEND/$NAME_DIR-$DATE_SUFFIX"

            if ls $PATH_BACKEND/$NAME_DIR-$DATE_SUFFIX ; then
                echo ""
                echo "#####################################################################################"
                echo ""
                echo "Копия ${PATH_BACKEND}/${NAME_DIR}-${DATE_SUFFIX} создана"
                echo ""
                echo "#####################################################################################"
                echo ""
            else
                echo ""
                echo "########################################################"
                echo ""
                echo "Копии ${NAME_DIR} не существует"
                echo ""
                echo "########################################################"
                echo ""
            fi
            echo ""
            echo "###############################################"
            echo ""
            echo "Обновление ${NAME_BACKEND}"
            echo ""
            echo "###############################################"
            echo ""

            cp -vpr "$PATCH_DIR/Patch/$NAME_DIR/"* $PATH_BACKEND/$NAME_DIR
            chown cddisk:cddisk -R $PATH_BACKEND/$NAME_DIR
        fi
        
        supervisorctl start $NAME_DISTR:$NAME_SERVICE

        if supervisorctl status $NAME_DISTR:$NAME_SERVICE | grep RUNNING | wc -l ; then
            echo ""
            echo "########################################################################"
            echo ""
            echo "Обновление ${NAME_BACKEND} завершено, сервис запущен"
            echo ""
            echo "########################################################################"
            echo ""
        else
            echo ""
            echo "########################################"
            echo ""
            echo "Ошибка запуска ${NAME_BACKEND}"
            echo ""
            echo "########################################"
            echo ""
        fi
    else
        echo ""
        echo "######################################################"
        echo ""
        echo "Данного сервиса, ${NAME_DIR}, не установлено"
        echo ""
        echo "######################################################"
        echo ""

        exit 1
    fi
}

function update_cddisk_alt {

    # Проверка наличия аргумента

    if [ "$#" -ne 1 ]; then
        echo ""
        echo "Использование для обновления deb пакета cddisk, cdmail, contacts: $0 -b <путь_к_патчу.zip>"
        exit 1
    fi

    COUNT_CALENDAR=$(rpm -qa | grep calendar | wc -l)
    COUNT_CDMAIL=$(rpm -qa | grep cdmail | wc -l)
    COUNT_CDDISK=$(rpm -qa | grep cddisk | wc -l)
    if ! [ $COUNT_CDDISK -ge 1 ]; then
	echo "cddisk не установлен"
        exit 1
    fi

    sudo apt-get -y install jq

    # Данные для авторизации в PostgreSQL
    DB_PATH_PARAM=/opt/r7-office/Api/appsettings.json
    PSQL_HOST=$(grep -oP "Host=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_DB_NAME=$(grep -oP "Database=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_USER=$(grep -oP "Username=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PASS=$(grep -oP "Password=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PORT=$(grep -oP "Port=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);

    export PGPASSWORD=$PSQL_PASS
    echo "DB_HOST=$PSQL_HOST"
    echo "DB_PORT=$PSQL_PORT"
    echo "DB_NAME=$PSQL_DB_NAME"
    echo "DB_USER=$PSQL_USER"

    RABBITMQ_PATH_PARAM=/opt/r7-office/Processing/appsettings.json
    RABBITMQ_HOST_IN=$(grep -oP "\"host\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    RABBITMQ_USER_IN=$(grep -oP "\"username\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    RABBITMQ_PASS_IN=$(grep -oP "\"password\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    echo "RABBITMQ_HOST=$RABBITMQ_HOST_IN"
    echo "RABBITMQ_USER=$RABBITMQ_USER_IN"
    echo "RABBITMQ_PASS=$RABBITMQ_PASS_IN"

    NGINX_DS_PATH_PARAM=/etc/nginx/sites-enabled.d/ds.conf
    NGINX_ADMIN_PATH_PARAM=/etc/nginx/sites-available/admin
    NGINX_CALENDAR_PATH_PARAM=/etc/nginx/sites-available/calendar
    NGINX_CDDISK_PATH_PARAM=/etc/nginx/sites-available/cddisk
    NGINX_CDMAIL_PATH_PARAM=/etc/nginx/sites-available/cdmail
    NGINX_CONTACTS_PATH_PARAM=/etc/nginx/sites-available/contacts
    NGINX_PROJECTS_PATH_PARAM=/etc/nginx/sites-available/projects
    NGINX_PAGES_PATH_PARAM=/etc/nginx/sites-available/pages
    NGINX_FORMS_PATH_PARAM=/etc/nginx/sites-available/forms
    ADMIN_HTTPS=$(grep -oP "listen 443" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
    HTTPS=false
    if [ $ADMIN_HTTPS="443" ] ; then
	HTTPS=true
    fi
    PSQL_SERVER_INSTALLED=false
    PSQL_SERVER_CTR=$(rpm -qa | grep postgresql-server | wc -l)
    if [ $PSQL_SERVER_CTR -ge 1 ]; then
	PSQL_SERVER_INSTALLED=true
    fi
    ADMIN_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
    CALENDAR_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CALENDAR_PATH_PARAM | head -1 | cut -d' ' -f2);
    CDDISK_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CDDISK_PATH_PARAM | head -1 | cut -d' ' -f2);
    CDMAIL_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CDMAIL_PATH_PARAM | head -1 | cut -d' ' -f2);
    CONTACTS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CONTACTS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PROJECTS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_PROJECTS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PAGES_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_PAGES_PATH_PARAM | head -1 | cut -d' ' -f2);
    FORMS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_FORMS_PATH_PARAM | head -1 | cut -d' ' -f2);
    if [ $HTTPS=true ] ; then
	SSL_CERT=$(grep -oP "ssl_certificate /[^\";]*" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
	HOST_NAME=$(echo "$SSL_CERT" | sed "s#/etc/nginx/ssl/##g" | sed "s#.crt##g")
    fi
    if [ -z $HOST_NAME ] || [ $HOST_NAME = "" ]; then
        cddisk_site_domain=$(whiptail --title  "cddisk" --inputbox "Domain name:" 10 60 "local.ru" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus != 0 ];  then
            cddisk_site_domain="local.ru"
        fi
        HOST_NAME=$cddisk_site_domain
    fi
    DS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_DS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PREFIX_DS_NAME=$(echo "$DS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_ADMIN_NAME=$(echo "$ADMIN_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CALENDAR_NAME=$(echo "$CALENDAR_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_IN=$(echo "$CDDISK_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CDMAIL_NAME=$(echo "$CDMAIL_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CONTACTS_NAME=$(echo "$CONTACTS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_PROJECTS_NAME=$(echo "$PROJECTS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_PAGES_NAME=$(echo "$PAGES_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_FORMS_NAME=$(echo "$FORMS_SERVER_NAME" | sed "s#.$HOST_NAME##g")

    if [ -z $PREFIX_IN ] || [ $PREFIX_IN = "" ]; then
	cddisk_prefix_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for cddisk:" 10 60 "cddisk" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_prefix_name="cddisk"
	fi
	PREFIX_IN=$cddisk_prefix_name
    fi
    if [ -z $PREFIX_ADMIN_NAME ] || [ $PREFIX_ADMIN_NAME = "" ]; then
	cddisk_admin_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for admin:" 10 60 "admin" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_admin_name="admin"
	fi
	PREFIX_ADMIN_NAME=$cddisk_admin_name
    fi
    if [ -z $PREFIX_CONTACTS_NAME ] || [ $PREFIX_CONTACTS_NAME = "" ]; then
	cddisk_contacts_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for contacts:" 10 60 "contacts" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_contacts_name="contacts"
	fi
	PREFIX_CONTACTS_NAME=$cddisk_contacts_name
    fi
    if [ -z $PREFIX_PROJECTS_NAME ] || [ $PREFIX_PROJECTS_NAME = "" ]; then
	cddisk_projects_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for projects:" 10 60 "projects" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_projects_name="projects"
	fi
	PREFIX_PROJECTS_NAME=$cddisk_projects_name
    fi
    if [ -z $PREFIX_PAGES_NAME ] || [ $PREFIX_PAGES_NAME = "" ]; then
	cddisk_pages_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for pages:" 10 60 "pages" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_pages_name="pages"
	fi
	PREFIX_PAGES_NAME=$cddisk_pages_name
    fi
    if [ -z $PREFIX_FORMS_NAME ] || [ $PREFIX_FORMS_NAME = "" ]; then
	cddisk_forms_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for forms:" 10 60 "forms" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_forms_name="forms"
	fi
	PREFIX_FORMS_NAME=$cddisk_forms_name
    fi
    if [ $COUNT_CALENDAR -ge 1 ] & [ $COUNT_CDMAIL -ge 1 ]; then
	if [ -z $PREFIX_CDMAIL_NAME ] || [ $PREFIX_CDMAIL_NAME = "" ]; then
	    cddisk_cdmail_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for cdmail:" 10 60 "cdmail" 3>&1 1>&2 2>&3)
	    exitstatus=$?
	    if [ $exitstatus != 0 ];  then
		cddisk_cdmail_name="cdmail"
	    fi
	    PREFIX_CDMAIL_NAME=$cddisk_cdmail_name
	fi
	if [ -z $PREFIX_CALENDAR_NAME ] || [ $PREFIX_CALENDAR_NAME = "" ]; then
	    cddisk_calendar_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for calendar:" 10 60 "calendar" 3>&1 1>&2 2>&3)
	    exitstatus=$?
	    if [ $exitstatus != 0 ];  then
		cddisk_calendar_name="calendar"
	    fi
	    PREFIX_CALENDAR_NAME=$cddisk_calendar_name
	fi
    fi
    if [ -z $PREFIX_DS_NAME ] || [ $PREFIX_DS_NAME = "" ]; then
        cddisk_ds_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for DS:" 10 60 "ds" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus != 0 ];  then
            cddisk_ds_name="ds"
        fi
        PREFIX_DS_NAME=$cddisk_ds_name
    fi

    echo "HTTPS=$HTTPS"
    echo "PSQL_SERVER_INSTALLED=$PSQL_SERVER_INSTALLED"
    echo "HOST_NAME=$HOST_NAME"
    echo "PREFIX_ADMIN_NAME=$PREFIX_ADMIN_NAME"
    echo "PREFIX_CALENDAR_NAME=$PREFIX_CALENDAR_NAME"
    echo "PREFIX_IN=$PREFIX_IN"
    echo "PREFIX_CDMAIL_NAME=$PREFIX_CDMAIL_NAME"
    echo "PREFIX_CONTACTS_NAME=$PREFIX_CONTACTS_NAME"
    echo "PREFIX_PROJECTS_NAME=$PREFIX_PROJECTS_NAME"
    echo "PREFIX_PAGES_NAME=$PREFIX_PAGES_NAME"
    echo "PREFIX_FORMS_NAME=$PREFIX_FORMS_NAME"
    echo "PREFIX_DS_NAME=$PREFIX_DS_NAME"

    KEY_IN=""
    rabbit_pass=""

    export DB_TYPE="postgresql"
    export CREATE_DB="$PSQL_SERVER_INSTALLED"
    export DB_HOST="$PSQL_HOST"
    export DB_PORT="$PSQL_PORT"
    export DB_USER="$PSQL_USER"
    export DB_PWD="$PSQL_PASS"
    export DB_CREATE_USER="postgres"
    export DB_CREATE_PWD="$PSQL_PASS"
    export MAKE_HTTPS=$HTTPS
    export SITE_DOMAIN="$HOST_NAME"
    export CDDISK_NAME="$PREFIX_IN"
    export ADMIN_NAME="$PREFIX_ADMIN_NAME"
    export CONTACTS_NAME="$PREFIX_CONTACTS_NAME"
    export PREFIX_CDMAIL="$PREFIX_CDMAIL_NAME"
    export CDMAIL_NAME="$PREFIX_CDMAIL_NAME"
    export PREFIX_CALENDAR="$PREFIX_CALENDAR_NAME"
    export CALENDAR_NAME="$PREFIX_CALENDAR_NAME"
    export PROJECTS_NAME="$PREFIX_PROJECTS_NAME"
    export PAGES_NAME="$PREFIX_PAGES_NAME"
    export FORMS_NAME="$PREFIX_FORMS_NAME"
    export CORE_MACHINE_KEY="$KEY_IN"
    export DS_NAME="$DS_SERVER_NAME"
    export RABBITMQ_TEAM_PASS="$rabbit_pass"

    export RABBITMQ_HOST="$RABBITMQ_HOST_IN"
    export RABBITMQ_USER="$RABBITMQ_USER_IN"
    export RABBITMQ_PASS="$RABBITMQ_PASS_IN"

    export DOMAIN="$HOST_NAME"
    export UPGRADE="true"
    check_pages_forms_installed
    echo "PAGESCLIENTID_=$PAGESCLIENTID_"
    echo "PAGESCLIENTSECRET_=$PAGESCLIENTSECRET_"
    export PAGESCLIENTID="$PAGESCLIENTID_"
    export PAGESCLIENTSECRET="$PAGESCLIENTSECRET_"

    # Данные путей к патчу
    PATCH_FILE=$1
    
    # Распаковываем
    echo ""
    echo "##########################################"
    echo "######## Распаковка дистрибутива #########"
    echo "##########################################"
    echo ""
    echo ""

    unzip "$PATCH_FILE" -d $CDDISK_DIR

    echo ""
    echo ""
    echo "#######################################"
    echo "## Распаковка дистрибутива завершена ##"
    echo "#######################################"
    echo ""
    echo ""

    if [ $MAKE_OFFLINE = "true" ]; then
	# Подключаем оффлайн дистрибутивы
	install_offline
    fi

    # Останавливаем сервисы

    echo ""
    echo ""
    echo "########################################"
    echo "## Останавливаем сервисы дистрибутива ##"
    echo "########################################"
    echo ""
    echo ""

    supervisorctl stop all

    # Делаем бекап
    echo ""
    echo ""
    echo "########################################"
    echo "###### Бекапирование дистрибутива ######"
    echo "########################################"
    echo ""
    echo ""
    for backend in Api FileStorage SearchApi Service.Registry Sso.Api Processing
    do
        echo ""
        echo $backend
        cp -vpr $PATH_BACKEND/$backend "$PATH_BACKEND/$backend-$DATE_SUFFIX"
        if ls $PATH_BACKEND/$backend-$DATE_SUFFIX ; then 
            echo ""
            echo "############################################################################"
            echo ""
            echo "Копия ${PATH_BACKEND}/${backend}-${DATE_SUFFIX} создана"
            echo ""
            echo "############################################################################"
            echo ""
        else
            echo ""
            echo "########################################"
            echo ""
            echo "Копии ${backend} не существует"
            echo ""
            echo "########################################"
            echo ""
        fi
    done
    mkdir $BCKP_DIR_PREFIX
    cp -vpr $PATH_NGINX "$BCKP_DIR_PREFIX"
    if ls $BCKP_DIR_PREFIX/nginx ; then 
        echo ""
        echo "############################################################################"
        echo ""
        echo "Копия ${BCKP_DIR_PREFIX}/nginx создана"
        echo ""
        echo "############################################################################"
        echo ""
    else
        echo ""
        echo "########################################"
        echo ""
        echo "Копии ${BCKP_DIR_PREFIX}/nginx не существует"
        echo ""
        echo "########################################"
        echo ""
    fi
    cp -vpr $PATH_SUPERVISOR_ALT "$BCKP_DIR_PREFIX"
    if ls $BCKP_DIR_PREFIX/supervisord.d ; then
        echo ""
        echo "############################################################################"
        echo ""
        echo "Копия ${BCKP_DIR_PREFIX}/supervisord.d создана"
        echo ""
        echo "############################################################################"
        echo ""
    else
        echo ""
        echo "########################################"
        echo ""
        echo "Копии ${BCKP_DIR_PREFIX}/supervisord.d не существует"
        echo ""
        echo "########################################"
        echo ""
    fi

    # Запустить сервисы
    echo ""
    echo ""
    echo "#################################"
    echo "####### Запуск сервисов #########"
    echo "#################################"
    echo ""
    echo ""

    supervisorctl start all

    # Обновляем дистрибутив
    echo ""
    echo ""
    echo "######################################"
    echo "###### Обновление дистрибутива #######"
    echo "######################################"
    echo ""
    echo ""

    NOW_DIR=$PWD
    echo "NOW_DIR $NOW_DIR"

    cd $CDDISK_DIR/CDDisk
    apt-get install -y java-17-openjdk
    apt-get install -y ./cddisk-*.rpm
    if [ $COUNT_CALENDAR -ge 1 ] & [ $COUNT_CDMAIL -ge 1 ]; then
	if [ $HTTPS=true ]; then
	    mkdir /var/tmp/sslcert
	fi
	apt-get install -y ./calendar*.rpm
	apt-get install -y ./cdmail*.rpm
	if [ $HTTPS=true ]; then
	    rmdir /var/tmp/sslcert
	fi
    fi
    cd $NOW_DIR

    if [ $MAKE_OFFLINE = "true" ]; then
	# Отключаем оффлайн дистрибутивы
	uninstall_offline
    fi

    cp -f $PATH_BACKEND/Api-$DATE_SUFFIX/appsettings.json /opt/r7-office/Api
    cp -f $PATH_BACKEND/Api-$DATE_SUFFIX/filestorage.json /opt/r7-office/Api
    cp -f $PATH_BACKEND/FileStorage-$DATE_SUFFIX/appsettings.json /opt/r7-office/FileStorage
    cp -f $PATH_BACKEND/FileStorage-$DATE_SUFFIX/filestorage.json /opt/r7-office/FileStorage

    sleep 5
    version_back=$(curl http://localhost:38033/api/v1/version 2>/dev/null | jq .Version)
    echo ""
    echo ""
    echo "#################################"
    echo "## Версия Api:${version_back} ###"
    echo "#################################"
    echo ""
    echo ""

}

function update_cddisk_rpm {

    # Проверка наличия аргумента

    if [ "$#" -ne 1 ]; then
        echo ""
        echo "Использование для обновления deb пакета cddisk, cdmail, contacts: $0 -b <путь_к_патчу.zip>"
        exit 1
    fi

    COUNT_CALENDAR=$(dnf list installed | grep calendar | wc -l)
    COUNT_CDMAIL=$(dnf list installed | grep cdmail | wc -l)
    COUNT_CDDISK=$(dnf list installed | grep cddisk | wc -l)
    if ! [ $COUNT_CDDISK -ge 1 ]; then
	echo "cddisk не установлен"
        exit 1
    fi

    # Данные для авторизации в PostgreSQL
    DB_PATH_PARAM=/opt/r7-office/Api/appsettings.json
    PSQL_HOST=$(grep -oP "Host=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_DB_NAME=$(grep -oP "Database=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_USER=$(grep -oP "Username=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PASS=$(grep -oP "Password=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PORT=$(grep -oP "Port=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);

    export PGPASSWORD=$PSQL_PASS
    echo "DB_HOST=$PSQL_HOST"
    echo "DB_PORT=$PSQL_PORT"
    echo "DB_NAME=$PSQL_DB_NAME"
    echo "DB_USER=$PSQL_USER"

    RABBITMQ_PATH_PARAM=/opt/r7-office/Processing/appsettings.json
    RABBITMQ_HOST_IN=$(grep -oP "\"host\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    RABBITMQ_USER_IN=$(grep -oP "\"username\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    RABBITMQ_PASS_IN=$(grep -oP "\"password\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    echo "RABBITMQ_HOST=$RABBITMQ_HOST_IN"
    echo "RABBITMQ_USER=$RABBITMQ_USER_IN"
    echo "RABBITMQ_PASS=$RABBITMQ_PASS_IN"

    NGINX_DS_PATH_PARAM=/etc/nginx/conf.d/ds.conf
    NGINX_ADMIN_PATH_PARAM=/etc/nginx/sites-available/admin
    NGINX_CALENDAR_PATH_PARAM=/etc/nginx/sites-available/calendar
    NGINX_CDDISK_PATH_PARAM=/etc/nginx/sites-available/cddisk
    NGINX_CDMAIL_PATH_PARAM=/etc/nginx/sites-available/cdmail
    NGINX_CONTACTS_PATH_PARAM=/etc/nginx/sites-available/contacts
    NGINX_PROJECTS_PATH_PARAM=/etc/nginx/sites-available/projects
    NGINX_PAGES_PATH_PARAM=/etc/nginx/sites-available/pages
    NGINX_FORMS_PATH_PARAM=/etc/nginx/sites-available/forms
    ADMIN_HTTPS=$(grep -oP "listen 443" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
    HTTPS=false
    if [ $ADMIN_HTTPS="443" ] ; then
	HTTPS=true
    fi
    PSQL_SERVER_INSTALLED=false
    PSQL_SERVER_CTR=$(dnf list installed | grep postgresql-server | wc -l)
    if [ $PSQL_SERVER_CTR -ge 1 ]; then
	PSQL_SERVER_INSTALLED=true
    fi
    ADMIN_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
    CALENDAR_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CALENDAR_PATH_PARAM | head -1 | cut -d' ' -f2);
    CDDISK_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CDDISK_PATH_PARAM | head -1 | cut -d' ' -f2);
    CDMAIL_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CDMAIL_PATH_PARAM | head -1 | cut -d' ' -f2);
    CONTACTS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CONTACTS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PROJECTS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_PROJECTS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PAGES_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_PAGES_PATH_PARAM | head -1 | cut -d' ' -f2);
    FORMS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_FORMS_PATH_PARAM | head -1 | cut -d' ' -f2);
    if [ $HTTPS=true ] ; then
	SSL_CERT=$(grep -oP "ssl_certificate /[^\";]*" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
	HOST_NAME=$(echo "$SSL_CERT" | sed "s#/etc/nginx/ssl/##g" | sed "s#.crt##g")
    fi
    if [ -z $HOST_NAME ] || [ $HOST_NAME = "" ]; then
        cddisk_site_domain=$(whiptail --title  "cddisk" --inputbox "Domain name:" 10 60 "local.ru" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus != 0 ];  then
            cddisk_site_domain="local.ru"
        fi
        HOST_NAME=$cddisk_site_domain
    fi
    DS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_DS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PREFIX_DS_NAME=$(echo "$DS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_ADMIN_NAME=$(echo "$ADMIN_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CALENDAR_NAME=$(echo "$CALENDAR_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_IN=$(echo "$CDDISK_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CDMAIL_NAME=$(echo "$CDMAIL_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CONTACTS_NAME=$(echo "$CONTACTS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_PROJECTS_NAME=$(echo "$PROJECTS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_PAGES_NAME=$(echo "$PAGES_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_FORMS_NAME=$(echo "$FORMS_SERVER_NAME" | sed "s#.$HOST_NAME##g")

    if [ -z $PREFIX_IN ] || [ $PREFIX_IN = "" ]; then
	cddisk_prefix_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for cddisk:" 10 60 "cddisk" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_prefix_name="cddisk"
	fi
	PREFIX_IN=$cddisk_prefix_name
    fi
    if [ -z $PREFIX_ADMIN_NAME ] || [ $PREFIX_ADMIN_NAME = "" ]; then
	cddisk_admin_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for admin:" 10 60 "admin" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_admin_name="admin"
	fi
	PREFIX_ADMIN_NAME=$cddisk_admin_name
    fi
    if [ -z $PREFIX_CONTACTS_NAME ] || [ $PREFIX_CONTACTS_NAME = "" ]; then
	cddisk_contacts_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for contacts:" 10 60 "contacts" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_contacts_name="contacts"
	fi
	PREFIX_CONTACTS_NAME=$cddisk_contacts_name
    fi
    if [ -z $PREFIX_PROJECTS_NAME ] || [ $PREFIX_PROJECTS_NAME = "" ]; then
	cddisk_projects_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for projects:" 10 60 "projects" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_projects_name="projects"
	fi
	PREFIX_PROJECTS_NAME=$cddisk_projects_name
    fi
    if [ -z $PREFIX_PAGES_NAME ] || [ $PREFIX_PAGES_NAME = "" ]; then
	cddisk_pages_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for pages:" 10 60 "pages" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_pages_name="pages"
	fi
	PREFIX_PAGES_NAME=$cddisk_pages_name
    fi
    if [ -z $PREFIX_FORMS_NAME ] || [ $PREFIX_FORMS_NAME = "" ]; then
	cddisk_forms_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for forms:" 10 60 "forms" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_forms_name="forms"
	fi
	PREFIX_FORMS_NAME=$cddisk_forms_name
    fi
    if [ $COUNT_CALENDAR -ge 1 ] & [ $COUNT_CDMAIL -ge 1 ]; then
	if [ -z $PREFIX_CDMAIL_NAME ] || [ $PREFIX_CDMAIL_NAME = "" ]; then
	    cddisk_cdmail_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for cdmail:" 10 60 "cdmail" 3>&1 1>&2 2>&3)
	    exitstatus=$?
	    if [ $exitstatus != 0 ];  then
		cddisk_cdmail_name="cdmail"
	    fi
	    PREFIX_CDMAIL_NAME=$cddisk_cdmail_name
	fi
	if [ -z $PREFIX_CALENDAR_NAME ] || [ $PREFIX_CALENDAR_NAME = "" ]; then
	    cddisk_calendar_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for calendar:" 10 60 "calendar" 3>&1 1>&2 2>&3)
	    exitstatus=$?
	    if [ $exitstatus != 0 ];  then
		cddisk_calendar_name="calendar"
	    fi
	    PREFIX_CALENDAR_NAME=$cddisk_calendar_name
	fi
    fi
    if [ -z $PREFIX_DS_NAME ] || [ $PREFIX_DS_NAME = "" ]; then
        cddisk_ds_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for DS:" 10 60 "ds" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus != 0 ];  then
            cddisk_ds_name="ds"
        fi
        PREFIX_DS_NAME=$cddisk_ds_name
    fi

    echo "HTTPS=$HTTPS"
    echo "PSQL_SERVER_INSTALLED=$PSQL_SERVER_INSTALLED"
    echo "HOST_NAME=$HOST_NAME"
    echo "PREFIX_ADMIN_NAME=$PREFIX_ADMIN_NAME"
    echo "PREFIX_CALENDAR_NAME=$PREFIX_CALENDAR_NAME"
    echo "PREFIX_IN=$PREFIX_IN"
    echo "PREFIX_CDMAIL_NAME=$PREFIX_CDMAIL_NAME"
    echo "PREFIX_CONTACTS_NAME=$PREFIX_CONTACTS_NAME"
    echo "PREFIX_PROJECTS_NAME=$PREFIX_PROJECTS_NAME"
    echo "PREFIX_PAGES_NAME=$PREFIX_PAGES_NAME"
    echo "PREFIX_FORMS_NAME=$PREFIX_FORMS_NAME"
    echo "PREFIX_DS_NAME=$PREFIX_DS_NAME"

    KEY_IN=""
    rabbit_pass=""

    export DB_TYPE="postgresql"
    export CREATE_DB="$PSQL_SERVER_INSTALLED"
    export DB_HOST="$PSQL_HOST"
    export DB_PORT="$PSQL_PORT"
    export DB_USER="$PSQL_USER"
    export DB_PWD="$PSQL_PASS"
    export DB_CREATE_USER="postgres"
    export DB_CREATE_PWD="$PSQL_PASS"
    export MAKE_HTTPS=$HTTPS
    export SITE_DOMAIN="$HOST_NAME"
    export CDDISK_NAME="$PREFIX_IN"
    export ADMIN_NAME="$PREFIX_ADMIN_NAME"
    export CONTACTS_NAME="$PREFIX_CONTACTS_NAME"
    export PREFIX_CDMAIL="$PREFIX_CDMAIL_NAME"
    export CDMAIL_NAME="$PREFIX_CDMAIL_NAME"
    export PREFIX_CALENDAR="$PREFIX_CALENDAR_NAME"
    export CALENDAR_NAME="$PREFIX_CALENDAR_NAME"
    export PROJECTS_NAME="$PREFIX_PROJECTS_NAME"
    export PAGES_NAME="$PREFIX_PAGES_NAME"
    export FORMS_NAME="$PREFIX_FORMS_NAME"
    export CORE_MACHINE_KEY="$KEY_IN"
    export DS_NAME="$DS_SERVER_NAME"
    export RABBITMQ_TEAM_PASS="$rabbit_pass"

    export RABBITMQ_HOST="$RABBITMQ_HOST_IN"
    export RABBITMQ_USER="$RABBITMQ_USER_IN"
    export RABBITMQ_PASS="$RABBITMQ_PASS_IN"

    export DOMAIN="$HOST_NAME"
    export UPGRADE="true"
    check_pages_forms_installed
    echo "PAGESCLIENTID_=$PAGESCLIENTID_"
    echo "PAGESCLIENTSECRET_=$PAGESCLIENTSECRET_"
    export PAGESCLIENTID="$PAGESCLIENTID_"
    export PAGESCLIENTSECRET="$PAGESCLIENTSECRET_"

    # Данные путей к патчу
    PATCH_FILE=$1

    # Распаковываем
    echo ""
    echo "##########################################"
    echo "######## Распаковка дистрибутива #########"
    echo "##########################################"
    echo ""
    echo ""

    unzip "$PATCH_FILE" -d $CDDISK_DIR

    echo ""
    echo ""
    echo "#######################################"
    echo "## Распаковка дистрибутива завершена ##"
    echo "#######################################"
    echo ""
    echo ""

    if [ $MAKE_OFFLINE = "true" ]; then
	# Подключаем оффлайн дистрибутивы
	install_offline
    fi

    # Останавливаем сервисы

    echo ""
    echo ""
    echo "########################################"
    echo "## Останавливаем сервисы дистрибутива ##"
    echo "########################################"
    echo ""
    echo ""

    supervisorctl stop all

    # Делаем бекап
    echo ""
    echo ""
    echo "########################################"
    echo "###### Бекапирование дистрибутива ######"
    echo "########################################"
    echo ""
    echo ""
    for backend in Api FileStorage SearchApi Service.Registry Sso.Api Processing
    do
        echo ""
        echo $backend
        cp -vpr $PATH_BACKEND/$backend "$PATH_BACKEND/$backend-$DATE_SUFFIX"
        if ls $PATH_BACKEND/$backend-$DATE_SUFFIX ; then 
            echo ""
            echo "############################################################################"
            echo ""
            echo "Копия ${PATH_BACKEND}/${backend}-${DATE_SUFFIX} создана"
            echo ""
            echo "############################################################################"
            echo ""
        else
            echo ""
            echo "########################################"
            echo ""
            echo "Копии ${backend} не существует"
            echo ""
            echo "########################################"
            echo ""
        fi
    done
    mkdir $BCKP_DIR_PREFIX
    cp -vpr $PATH_NGINX "$BCKP_DIR_PREFIX"
    if ls $BCKP_DIR_PREFIX/nginx ; then 
        echo ""
        echo "############################################################################"
        echo ""
        echo "Копия ${BCKP_DIR_PREFIX}/nginx создана"
        echo ""
        echo "############################################################################"
        echo ""
    else
        echo ""
        echo "########################################"
        echo ""
        echo "Копии ${BCKP_DIR_PREFIX}/nginx не существует"
        echo ""
        echo "########################################"
        echo ""
    fi
    cp -vpr $PATH_SUPERVISOR_REDOS "$BCKP_DIR_PREFIX"
    if ls $BCKP_DIR_PREFIX/supervisord.d ; then
        echo ""
        echo "############################################################################"
        echo ""
        echo "Копия ${BCKP_DIR_PREFIX}/supervisord.d создана"
        echo ""
        echo "############################################################################"
        echo ""
    else
        echo ""
        echo "########################################"
        echo ""
        echo "Копии ${BCKP_DIR_PREFIX}/supervisord.d не существует"
        echo ""
        echo "########################################"
        echo ""
    fi

    # Запустить сервисы
    echo ""
    echo ""
    echo "#################################"
    echo "####### Запуск сервисов #########"
    echo "#################################"
    echo ""
    echo ""

    supervisorctl start all

    # Обновляем дистрибутив
    echo ""
    echo ""
    echo "######################################"
    echo "###### Обновление дистрибутива #######"
    echo "######################################"
    echo ""
    echo ""

    NOW_DIR=$PWD
    echo "NOW_DIR $NOW_DIR"

    cd $CDDISK_DIR/CDDisk
    dnf install -y --best --allowerasing java-17-openjdk
    dnf install --noautoremove -y ./cddisk*.rpm
    if [ $COUNT_CALENDAR -ge 1 ] & [ $COUNT_CDMAIL -ge 1 ]; then
	if [ $HTTPS=true ]; then
	    mkdir /var/tmp/sslcert
	fi
	dnf install --noautoremove -y ./calendar*.rpm
	dnf install --noautoremove -y ./cdmail*.rpm
	if [ $HTTPS=true ]; then
	    rmdir /var/tmp/sslcert
	fi
    fi
    cd $NOW_DIR

    if [ $MAKE_OFFLINE = "true" ]; then
	# Отключаем оффлайн дистрибутивы
	uninstall_offline
    fi

    cp -f $PATH_BACKEND/Api-$DATE_SUFFIX/appsettings.json /opt/r7-office/Api
    cp -f $PATH_BACKEND/Api-$DATE_SUFFIX/filestorage.json /opt/r7-office/Api
    cp -f $PATH_BACKEND/FileStorage-$DATE_SUFFIX/appsettings.json /opt/r7-office/FileStorage
    cp -f $PATH_BACKEND/FileStorage-$DATE_SUFFIX/filestorage.json /opt/r7-office/FileStorage

    sleep 5
    version_back=$(curl http://localhost:38033/api/v1/version 2>/dev/null | jq .Version)
    echo ""
    echo ""
    echo "#################################"
    echo "## Версия Api:${version_back} ###"
    echo "#################################"
    echo ""
    echo ""
}

function update_cddisk {

    # Проверка наличия аргумента

    if [ "$#" -ne 1 ]; then
        echo ""
        echo "Использование для обновления deb пакета cddisk, cdmail, contacts: $0 -b <путь_к_патчу.zip>"
        exit 1
    fi

    COUNT_CDDISK=$(apt list | grep cddisk | wc -l)
    COUNT_CALENDAR=$(apt list | grep cddisk-calendar | wc -l)
    COUNT_CDMAIL=$(apt list | grep cdmail | wc -l)
    if ! [ $COUNT_CDDISK -ge 1 ]; then
	echo "cddisk не установлен"
        exit 1
    fi

    # Данные для авторизации в PostgreSQL
    DB_PATH_PARAM=/opt/r7-office/Api/appsettings.json
    PSQL_HOST=$(grep -oP "Host=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_DB_NAME=$(grep -oP "Database=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_USER=$(grep -oP "Username=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PASS=$(grep -oP "Password=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);
    PSQL_PORT=$(grep -oP "Port=[^\";]*" $DB_PATH_PARAM | head -1 | cut -d'=' -f2);

    export PGPASSWORD=$PSQL_PASS
    echo "DB_HOST=$PSQL_HOST"
    echo "DB_PORT=$PSQL_PORT"
    echo "DB_NAME=$PSQL_DB_NAME"
    echo "DB_USER=$PSQL_USER"

    RABBITMQ_PATH_PARAM=/opt/r7-office/Processing/appsettings.json
    RABBITMQ_HOST_IN=$(grep -oP "\"host\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    RABBITMQ_USER_IN=$(grep -oP "\"username\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    RABBITMQ_PASS_IN=$(grep -oP "\"password\": \"[^\",]*" $RABBITMQ_PATH_PARAM | head -1 | cut -d' ' -f2 | sed "s#\"##g");
    echo "RABBITMQ_HOST=$RABBITMQ_HOST_IN"
    echo "RABBITMQ_USER=$RABBITMQ_USER_IN"
    echo "RABBITMQ_PASS=$RABBITMQ_PASS_IN"

    NGINX_DS_PATH_PARAM=/etc/nginx/conf.d/ds.conf
    NGINX_ADMIN_PATH_PARAM=/etc/nginx/sites-available/admin
    NGINX_CALENDAR_PATH_PARAM=/etc/nginx/sites-available/calendar
    NGINX_CDDISK_PATH_PARAM=/etc/nginx/sites-available/cddisk
    NGINX_CDMAIL_PATH_PARAM=/etc/nginx/sites-available/cdmail
    NGINX_CONTACTS_PATH_PARAM=/etc/nginx/sites-available/contacts
    NGINX_PROJECTS_PATH_PARAM=/etc/nginx/sites-available/projects
    ADMIN_HTTPS=$(grep -oP "listen 443" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
    HTTPS=false
    if [ $ADMIN_HTTPS="443" ] ; then
	HTTPS=true
    fi
    PSQL_SERVER_INSTALLED=false
    if [ $MAKE_OFFLINE = "true" ]; then
        PSQL_SERVER_CTR=$(apt list | grep postgresql | wc -l)
    else
        PSQL_SERVER_CTR=$(apt list | grep postgresql-server | wc -l)
    fi
    if [ $PSQL_SERVER_CTR -ge 1 ]; then
	PSQL_SERVER_INSTALLED=true
    fi
    ADMIN_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
    CALENDAR_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CALENDAR_PATH_PARAM | head -1 | cut -d' ' -f2);
    CDDISK_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CDDISK_PATH_PARAM | head -1 | cut -d' ' -f2);
    CDMAIL_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CDMAIL_PATH_PARAM | head -1 | cut -d' ' -f2);
    CONTACTS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_CONTACTS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PROJECTS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_PROJECTS_PATH_PARAM | head -1 | cut -d' ' -f2);
    if [ $HTTPS=true ] ; then
	SSL_CERT=$(grep -oP "ssl_certificate /[^\";]*" $NGINX_ADMIN_PATH_PARAM | head -1 | cut -d' ' -f2);
	HOST_NAME=$(echo "$SSL_CERT" | sed "s#/etc/nginx/ssl/##g" | sed "s#.crt##g")
    fi
    if [ -z $HOST_NAME ] || [ $HOST_NAME = "" ]; then
        cddisk_site_domain=$(whiptail --title  "cddisk" --inputbox "Domain name:" 10 60 "local.ru" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus != 0 ];  then
            cddisk_site_domain="local.ru"
        fi
        HOST_NAME=$cddisk_site_domain
    fi
    DS_SERVER_NAME=$(grep -oP "server_name [^\";]*" $NGINX_DS_PATH_PARAM | head -1 | cut -d' ' -f2);
    PREFIX_DS_NAME=$(echo "$DS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_ADMIN_NAME=$(echo "$ADMIN_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CALENDAR_NAME=$(echo "$CALENDAR_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_IN=$(echo "$CDDISK_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CDMAIL_NAME=$(echo "$CDMAIL_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_CONTACTS_NAME=$(echo "$CONTACTS_SERVER_NAME" | sed "s#.$HOST_NAME##g")
    PREFIX_PROJECTS_NAME=$(echo "$PROJECTS_SERVER_NAME" | sed "s#.$HOST_NAME##g")

    if [ -z $PREFIX_IN ] || [ $PREFIX_IN = "" ]; then
	cddisk_prefix_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for cddisk:" 10 60 "cddisk" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_prefix_name="cddisk"
	fi
	PREFIX_IN=$cddisk_prefix_name
    fi
    if [ -z $PREFIX_ADMIN_NAME ] || [ $PREFIX_ADMIN_NAME = "" ]; then
	cddisk_admin_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for admin:" 10 60 "admin" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_admin_name="admin"
	fi
	PREFIX_ADMIN_NAME=$cddisk_admin_name
    fi
    if [ -z $PREFIX_CONTACTS_NAME ] || [ $PREFIX_CONTACTS_NAME = "" ]; then
	cddisk_contacts_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for contacts:" 10 60 "contacts" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_contacts_name="contacts"
	fi
	PREFIX_CONTACTS_NAME=$cddisk_contacts_name
    fi
    if [ -z $PREFIX_PROJECTS_NAME ] || [ $PREFIX_PROJECTS_NAME = "" ]; then
	cddisk_projects_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for projects:" 10 60 "projects" 3>&1 1>&2 2>&3)
	exitstatus=$?
	if [ $exitstatus != 0 ];  then
	    cddisk_projects_name="projects"
	fi
	PREFIX_PROJECTS_NAME=$cddisk_projects_name
    fi
    if [ $COUNT_CALENDAR -ge 1 ] & [ $COUNT_CDMAIL -ge 1 ]; then
	if [ -z $PREFIX_CDMAIL_NAME ] || [ $PREFIX_CDMAIL_NAME = "" ]; then
	    cddisk_cdmail_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for cdmail:" 10 60 "cdmail" 3>&1 1>&2 2>&3)
	    exitstatus=$?
	    if [ $exitstatus != 0 ];  then
		cddisk_cdmail_name="cdmail"
	    fi
	    PREFIX_CDMAIL_NAME=$cddisk_cdmail_name
	fi
	if [ -z $PREFIX_CALENDAR_NAME ] || [ $PREFIX_CALENDAR_NAME = "" ]; then
	    cddisk_calendar_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for calendar:" 10 60 "calendar" 3>&1 1>&2 2>&3)
	    exitstatus=$?
	    if [ $exitstatus != 0 ];  then
		cddisk_calendar_name="calendar"
	    fi
	    PREFIX_CALENDAR_NAME=$cddisk_calendar_name
	fi
    fi
    if [ -z $PREFIX_DS_NAME ] || [ $PREFIX_DS_NAME = "" ]; then
        cddisk_ds_name=$(whiptail --title  "cddisk" --inputbox "Prefix name for DS:" 10 60 "ds" 3>&1 1>&2 2>&3)
        exitstatus=$?
        if [ $exitstatus != 0 ];  then
            cddisk_ds_name="ds"
        fi
        PREFIX_DS_NAME=$cddisk_ds_name
    fi

    echo "HTTPS=$HTTPS"
    echo "PSQL_SERVER_INSTALLED=$PSQL_SERVER_INSTALLED"
    echo "HOST_NAME=$HOST_NAME"
    echo "PREFIX_ADMIN_NAME=$PREFIX_ADMIN_NAME"
    echo "PREFIX_CALENDAR_NAME=$PREFIX_CALENDAR_NAME"
    echo "PREFIX_IN=$PREFIX_IN"
    echo "PREFIX_CDMAIL_NAME=$PREFIX_CDMAIL_NAME"
    echo "PREFIX_CONTACTS_NAME=$PREFIX_CONTACTS_NAME"
    echo "PREFIX_PROJECTS_NAME=$PREFIX_PROJECTS_NAME"
    echo "PREFIX_DS_NAME=$PREFIX_DS_NAME"

    # Данные путей к патчу
    PATCH_FILE=$1
    
    # Распаковываем
    echo ""
    echo "##########################################"
    echo "######## Распаковка дистрибутива #########"
    echo "##########################################"
    echo ""
    echo ""

    unzip "$PATCH_FILE" -d $CDDISK_DIR

    echo ""
    echo ""
    echo "#######################################"
    echo "## Распаковка дистрибутива завершена ##"
    echo "#######################################"
    echo ""
    echo ""

    if [ $MAKE_OFFLINE = "true" ]; then
	# Подключаем оффлайн дистрибутивы
	install_offline
    fi

    # Останавливаем сервисы

    echo ""
    echo ""
    echo "########################################"
    echo "## Останавливаем сервисы дистрибутива ##"
    echo "########################################"
    echo ""
    echo ""

    supervisorctl stop all

    # Делаем бекап
    echo ""
    echo ""
    echo "########################################"
    echo "###### Бекапирование дистрибутива ######"
    echo "########################################"
    echo ""
    echo ""
    for backend in Api FileStorage SearchApi Service.Registry Sso.Api Processing
    do
        echo ""
        echo $backend
        cp -vpr $PATH_BACKEND/$backend "$PATH_BACKEND/$backend-$DATE_SUFFIX"
        if ls $PATH_BACKEND/$backend-$DATE_SUFFIX ; then 
            echo ""
            echo "############################################################################"
            echo ""
            echo "Копия ${PATH_BACKEND}/${backend}-${DATE_SUFFIX} создана"
            echo ""
            echo "############################################################################"
            echo ""
        else
            echo ""
            echo "########################################"
            echo ""
            echo "Копии ${backend} не существует"
            echo ""
            echo "########################################"
            echo ""
        fi
    done
    mkdir $BCKP_DIR_PREFIX
    cp -vpr $PATH_NGINX "$BCKP_DIR_PREFIX"
    if ls $BCKP_DIR_PREFIX/nginx ; then 
        echo ""
        echo "############################################################################"
        echo ""
        echo "Копия ${BCKP_DIR_PREFIX}/nginx создана"
        echo ""
        echo "############################################################################"
        echo ""
    else
        echo ""
        echo "########################################"
        echo ""
        echo "Копии ${BCKP_DIR_PREFIX}/nginx не существует"
        echo ""
        echo "########################################"
        echo ""
    fi
    cp -vpr $PATH_SUPERVISOR "$BCKP_DIR_PREFIX"
    if ls $BCKP_DIR_PREFIX/supervisor ; then
        echo ""
        echo "############################################################################"
        echo ""
        echo "Копия ${BCKP_DIR_PREFIX}/supervisor создана"
        echo ""
        echo "############################################################################"
        echo ""
    else
        echo ""
        echo "########################################"
        echo ""
        echo "Копии ${BCKP_DIR_PREFIX}/supervisor не существует"
        echo ""
        echo "########################################"
        echo ""
    fi

    # Запустить сервисы
    echo ""
    echo ""
    echo "#################################"
    echo "####### Запуск сервисов #########"
    echo "#################################"
    echo ""
    echo ""

    supervisorctl start all

    # Обновляем дистрибутив
    echo ""
    echo ""
    echo "######################################"
    echo "###### Обновление дистрибутива #######"
    echo "######################################"
    echo ""
    echo ""

    NOW_DIR=$PWD
    echo "NOW_DIR $NOW_DIR"

    if [ $MAKE_OFFLINE = "true" ]; then
	cd $CDDISK_DIR/CDDiskPack/CDinstall_Astra_1.7.4/CDDisk
    else
	cd $CDDISK_DIR/CDDiskPack/CDinstall/CDDisk
    fi

    check_pages_forms_installed
    echo "PAGESCLIENTID_=$PAGESCLIENTID_"
    echo "PAGESCLIENTSECRET_=$PAGESCLIENTSECRET_"

    echo cddisk cddisk/fromscript boolean true | sudo debconf-set-selections
    echo cddisk cddisk/db-type select "postgresql" | sudo debconf-set-selections
    echo cddisk cddisk/db-create boolean $PSQL_SERVER_INSTALLED | sudo debconf-set-selections
    echo cddisk cddisk/db-host string $PSQL_HOST | sudo debconf-set-selections
    echo cddisk cddisk/db-port-postgresql string $PSQL_PORT | sudo debconf-set-selections
    echo cddisk cddisk/db-user string $PSQL_USER | sudo debconf-set-selections
    echo cddisk cddisk/db-pwd string $PSQL_PASS | sudo debconf-set-selections
    echo cddisk cddisk/db-create-user string "postgres" | sudo debconf-set-selections
    echo cddisk cddisk/db-create-pwd string $PSQL_PASS | sudo debconf-set-selections
    echo cddisk cddisk/core-machine-key string $KEY_IN | sudo debconf-set-selections
    echo cddisk cddisk/make-https boolean $HTTPS | sudo debconf-set-selections
    echo cddisk cddisk/site-domain string $HOST_NAME | sudo debconf-set-selections
    echo cddisk cddisk/cddisk-name string $PREFIX_IN | sudo debconf-set-selections
    echo cddisk cddisk/admin-name string $PREFIX_ADMIN_NAME | sudo debconf-set-selections
    echo cddisk cddisk/contacts-name string $PREFIX_CONTACTS_NAME | sudo debconf-set-selections
    echo cddisk cddisk/cdmail-name string $PREFIX_CDMAIL_NAME | sudo debconf-set-selections
    echo cddisk cddisk/calendar-name string $PREFIX_CALENDAR_NAME | sudo debconf-set-selections
    echo cddisk cddisk/projects-name string "projects" | sudo debconf-set-selections
    echo cddisk cddisk/ds-name string $PREFIX_DS_NAME | sudo debconf-set-selections
    echo CDDisk cddisk/upgrade boolean true | sudo debconf-set-selections
    echo cddisk cddisk/pages-client-id string $PAGESCLIENTID_ | sudo debconf-set-selections
    echo cddisk cddisk/pages-client-secret string $PAGESCLIENTSECRET_ | sudo debconf-set-selections
    apt-get install -y --only-upgrade ./CDDisk_*.deb
    echo CDDisk cddisk/upgrade boolean false | sudo debconf-set-selections
    if [ $COUNT_CALENDAR -ge 1 ] & [ $COUNT_CDMAIL -ge 1 ]; then
	if [ $MAKE_HTTPS="true" ]; then
	    mkdir /var/tmp/sslcert
	fi

	echo cdmail cdmail/is-prompt-domain boolean false | sudo debconf-set-selections
	echo cdmail cdmail/domain string $HOST_NAME | sudo debconf-set-selections
	echo cdmail cdmail/prefix string $PREFIX_CDMAIL_NAME | sudo debconf-set-selections
	echo cdmail cdmail/prefix-cddisk string $PREFIX_IN | sudo debconf-set-selections
	echo calendar calendar/domain string $HOST_NAME | sudo debconf-set-selections
	echo calendar calendar/prefix string $PREFIX_CALENDAR_NAME | sudo debconf-set-selections
	echo calendar calendar/cddisk-prefix string $PREFIX_IN | sudo debconf-set-selections
	apt-get install -y --only-upgrade ./cddisk-calendar_*.deb
	apt-get install -y --only-upgrade ./cdmail_*.deb
	if [ $MAKE_HTTPS="true" ]; then
	    rmdir /var/tmp/sslcert
	fi

	set +e
	nginxerror="$(systemctl status nginx | grep emerg | grep http2)"
	if [ -n "$nginxerror" ]; then
	    echo "Change nginx http2 back"
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/admin
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/cddisk
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/contacts
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/projects
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/forms
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/pages
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/calendar
	    sed -i "s#listen 443 ssl; http2 on;#listen 443 ssl http2;#g" /etc/nginx/sites-available/cdmail
	    systemctl restart nginx || true
	fi
	set -e
    fi
    cd $NOW_DIR

    if [ $MAKE_OFFLINE = "true" ]; then
	# Отключаем оффлайн дистрибутивы
	uninstall_offline
    fi

    cp -f $PATH_BACKEND/Api-$DATE_SUFFIX/appsettings.json /opt/r7-office/Api
    cp -f $PATH_BACKEND/Api-$DATE_SUFFIX/filestorage.json /opt/r7-office/Api
    cp -f $PATH_BACKEND/FileStorage-$DATE_SUFFIX/appsettings.json /opt/r7-office/FileStorage
    cp -f $PATH_BACKEND/FileStorage-$DATE_SUFFIX/filestorage.json /opt/r7-office/FileStorage

    sleep 5
    version_back=$(curl http://localhost:38033/api/v1/version 2>/dev/null | jq .Version)
    echo ""
    echo ""
    echo "#################################"
    echo "## Версия Api:${version_back} ###"
    echo "#################################"
    echo ""
    echo ""
}


function del_tmp {

    echo ""
    echo "#############################################################################"
    echo ""
    echo "Удаленение распакованного патча ${PATCH_DIR}"
    echo ""
    echo "#############################################################################"
    echo ""
    rm -rf $PATCH_DIR

}
function log_file {
    if [ $distr = deb ]; then
        cat $log_file | grep $NAME_SCRIPT > $LOG_FILE
    elif [ $distr = rpm ]; then
        cat $log_file | grep $NAME_SCRIPT > $LOG_FILE
    fi

    echo ""
    echo "##########################################################################"
    echo ""
    echo "лог файл: ${LOG_FILE}"
    echo ""
    echo "##########################################################################"
    echo ""

}

function yes_or_no {
    while true; do
        read -p "$1 [y/n]: " yn
        case $yn in
            [Yy]*) answer=0 ; return 0;;
            [Nn]*) answer=1 ; return 0;;
        esac
    done
}

DATE_SUFFIX=$(date +%d-%m-%Y%-H-%M-%N)
PATCH_DIR="/tmp/Patch_$DATE_SUFFIX"
BCKP_DIR_PREFIX="/tmp/Backup_$DATE_SUFFIX"
PATH_BACKEND=/opt/r7-office
PATH_NGINX=/etc/nginx
PATH_SUPERVISOR=/etc/supervisor
PATH_SUPERVISOR_ALT=/etc/supervisord.d
PATH_SUPERVISOR_REDOS=/etc/supervisord.d
NAME_DISTR=cddisk
NAME_SCRIPT=$0
LOG_FILE="/var/log/log-$DATE_SUFFIX-$NAME_SCRIPT.log"
CDDISK_DIR="/tmp/CDInstall_$DATE_SUFFIX"

# Инициализируем ОС
init_os
# Включаем логирование
log_write

while [ "$1" != "" ]; do

	case $1 in	

		-b | --backend  )
			if [ "$2" != "" ]; then
				check_installed
				update_backend "$2"
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления бэкенда: $0 -b <путь_к_патчу.zip>"
                echo ""
                echo ""
                shift
			fi
		;;

		-w | --web )
			if [ "$2" != "" ]; then
                if [ "$3" != "" ]; then
		    check_installed
                    update_web "$2" "$3"
                    log_file
				    shift
                else
                    echo ""
                    echo ""
                    echo "Использование для обновления фронта: $0 -w <имя_фронта> <путь_к_архиву.zip>"
                    shift
                fi
            else
                echo ""
                echo ""
                echo "Использование для обновления фронта: $0 -w <имя_фронта> <путь_к_архиву.zip>"
                shift
			fi
		;;

		-s | --single )
			if [ "$2" != "" ]; then
                if [ "$3" != "" ]; then
		    check_installed
                    update_single "$2" "$3"
                    log_file
                    del_tmp
				    shift
                else
                    echo ""
                    echo ""
                    echo "Использование для обновления фронта: $0 -s <имя_бэкенда> <путь_к_архиву.zip>"
                    shift
                fi
            else
                echo ""
                echo ""
                echo "Использование для обновления фронта: $0 -s <имя_бэкенда> <путь_к_архиву.zip>"
                shift
			fi
		;;

		-d | --database  )
			if [ "$2" != "" ]; then
				check_installed
				update_database "$2"
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления бэкенда: $0 -d <путь_к_патчу.zip>"
                shift
			fi
		;;

		-a | --all  )
			if [ "$2" != "" ]; then
		check_installed
                update_backend "$2"
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления бэкенда: $0 -d <путь_к_патчу.zip>"
                shift
			fi
		;;

		-f | --front  )
			if [ "$2" != "" ]; then
                PATCH_FILE=$2
		check_installed
                unzip "$PATCH_FILE" -d $PATCH_DIR
                update_all_web
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления фронта: $0 -d <путь_к_патчу.zip>"
                shift
			fi
		;;

		-c | --cddiskdeb  )
			if [ "$3" == "--offline" ]; then
			    MAKE_OFFLINE="true"
			    echo ""
			    echo ""
			    echo "Выполнение оффлайн устновки"
			    echo ""
			    echo ""
			else
			    check_installed
			fi
			if [ "$2" != "" ]; then
				update_cddisk "$2"
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления дистрибутива: $0 -c <путь_к_дистрибутиву.zip> [--offline]"
                echo ""
                echo ""
                shift
			fi
		;;

		-r | --cddiskrpm  )
			if [ "$3" == "--offline" ]; then
			    MAKE_OFFLINE="true"
			    echo ""
			    echo ""
			    echo "Выполнение оффлайн устновки"
			    echo ""
			    echo ""
			else
			    check_installed
			fi
			if [ "$2" != "" ]; then
				update_cddisk_rpm "$2"
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления дистрибутива: $0 -c <путь_к_дистрибутиву.zip> [--offline]"
                echo ""
                echo ""
                shift
			fi
		;;

		-l | --cddiskalt  )
			if [ "$3" == "--offline" ]; then
			    MAKE_OFFLINE="true"
			    echo ""
			    echo ""
			    echo "Выполнение оффлайн устновки"
			    echo ""
			    echo ""
			else
			    check_installed
			fi
			if [ "$2" != "" ]; then
				update_cddisk_alt "$2"
                log_file
                del_tmp
				shift
            else
                echo ""
                echo ""
                echo "Использование для обновления дистрибутива: $0 -c <путь_к_дистрибутиву.zip> [--offline]"
                echo ""
                echo ""
                shift
			fi
		;;

		-? | -h | --help )
            echo ""
            echo "################################################################################################################################################################################################################"
			echo "  Используйте $0 [PARAMETER] [[PARAMETER], ...]"
			echo "  Параметры:"
			echo "      -b, --backend      | Для обновления бэкенда | Пример использование: bash update.sh -b /tmp/Patch_2.0.15.1949.zip | Примечание: Используется при инсталляяции на одном сервере api, processing, api.sso"
			echo "      -w, --web          | Для обновления фронта admin|calendar|cddisk|cdmail|contacts | Пример использования: bash update.sh -w admin /tmp/mail_2211.zip"
            echo "      -s, --single       | Для обновления фронта sso|api|processing|fs|sr|search | Пример использования: bash update.sh -s sso /tmp/Patch_2.0.15.1949.zip или bash update.sh -s sso /tmp/FS_3.150.zip"
            echo "      -d, --database     | Для обновления БД | Пример использование: bash update.sh -d /tmp/Patch_2.0.15.1949.zip | ВАЖНО: Использовать только на сервере, где есть сервис API" 
            echo "      -a, --all          | Для обновления БД,бэкенда и фронта admin|calendar|cddisk|cdmail|contacts | Пример использования: bash update.sh -a /tmp/Patch_2.0.15.1949.zip"
            echo "      -f, --front        | Для обновления фронта admin|calendar|cddisk|cdmail|contacts | Пример использования: bash update.sh -f /tmp/Patch_2.0.15.1949.zip"
            echo "      -c, --cddiskdeb    | Для обновления deb пакета cddisk,cdmail,contacts | Пример использования: bash update.sh -c /tmp/CDInstall_2.0.15.10949.zip [--offline]"
            echo "      -r, --cddiskrpm    | Для обновления rpm пакета cddisk,cdmail,contacts | Пример использования: bash update.sh -r /tmp/RedOS_2.0.15.10949.zip [--offline]"
            echo "      -l, --cddiskalt    | Для обновления rpm пакета cddisk,cdmail,contacts | Пример использования: bash update.sh -l /tmp/AltServer_2.0.15.10949.zip [--offline]"
			echo "      -?, -h, --help     | справка"
            echo "################################################################################################################################################################################################################"
			echo ""
			exit 0
		;;

	esac

	shift

done
