#!/bin/bash

function Exit()
{
    echo -e ${RED}"Ошибка!"${NOCOLOR}
    read -n 1 -s -r -p "Нажмите любую клавишу..."
    exit 1
}

set -e
CURRENT_USER=${SUDO_USER:-${USER}}

if ! type pg_config &> /dev/null;
then
    PGSQL_BIN="/usr/bin/"
else
    PGSQL_BIN=$(pg_config --bindir)"/"
fi

RED='\033[0;31m'
GREEN='\033[0;32m'
NOCOLOR='\033[0m'
HAS_CONFIG=0

echo -e ${GREEN}"Конфигурация репозитория"${NOCOLOR}
# checking for existing config
if [ -f /home/$CURRENT_USER/.local/share/Credo-Dialogue/CredoRepository/config.xml ];
then
    read -r -p "Найден конфигурационный файл. Использовать его? [y/N] " response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
    then
        PG_PORT=$(xmllint --xpath '//config/storage/db/port/text()' /home/$CURRENT_USER/.local/share/Credo-Dialogue/CredoRepository/config.xml)
        REPO_FOLDER=$(xmllint --xpath '//config/storage/path/text()' /home/$CURRENT_USER/.local/share/Credo-Dialogue/CredoRepository/config.xml)
        HAS_CONFIG=1
    fi
fi
if [ $HAS_CONFIG = 0 ];
then
    read -p "$(echo -e ${RED}"Имя сервера: "${NOCOLOR})" SERVER_NAME
    read -e -p "$(echo -e ${RED}"Директория репозитория: "${NOCOLOR})" -i "CredoStorage" REPO_FOLDER_TITLE
    REPO_FOLDER="/home/"$CURRENT_USER"/"$REPO_FOLDER_TITLE
    unset PASS_ROOT
    while [ -z ${PASS_ROOT} ]; do
         read -s -p "$(echo -e ${RED}"Пароль администратора: "${NOCOLOR})" PASS_ROOT
         echo ""
    done

    echo -e -e ${GREEN}"Сетевые настройки"${NOCOLOR}
    read -e -p "$(echo -e ${RED}"Свободный порт на localhost: "${NOCOLOR})" -i "45432" PG_PORT
    read -e -p "$(echo -e ${RED}"Сетевой интерфейс для входящих соединений\n(укажите * для открытия порта на всех доступных интерфейсах): "${NOCOLOR})" -i "*" SERVER_IFACE
    read -e -p "$(echo -e ${RED}"Порт для входящих соединений: "${NOCOLOR})" -i "41800" SERVER_PORT

    if [ -z "$SERVER_NAME" ];
    then
        SERVER_NAME=$REPO_FOLDER_TITLE
    fi
fi
echo -e "${RED}Владелец:${NOCOLOR} " $CURRENT_USER
echo -e "${RED}Путь к PostgreSQL:${NOCOLOR} " $PGSQL_BIN

DB_FOLDER=$REPO_FOLDER"/db"
BLOBS_FOLDER=$REPO_FOLDER"/blobs"

create_new=1

if [ -d $DB_FOLDER ] && [ -d $BLOBS_FOLDER ];
then
    echo "Найдена база данных."
    create_new=0
fi

if [ $create_new -eq 1 ] && [ -d $REPO_FOLDER ];
then
    echo "В выбранной папке невозможно создать хранилище. Укажите путь к существующему хранилищу или путь, где создать новое.."
    Exit
fi

if [ $create_new -eq 1 ];
then
    echo -e ${GREEN}"Создаем каталоги: $REPO_FOLDER $BLOBS_FOLDER"${NOCOLOR}

    if [ -d $REPO_FOLDER ]
    then
        echo "$REPO_FOLDER существует"
        rm -r -f $REPO_FOLDER
    fi
    sudo -u $CURRENT_USER mkdir -p $REPO_FOLDER
    sudo -u $CURRENT_USER mkdir -p $BLOBS_FOLDER

    if [ -d $REPO_FOLDER ] && [ -d $BLOBS_FOLDER ]
    then
        echo "Успешно"
    else
        echo "Ошибка создания"
        Exit
    fi

    echo -e ${GREEN}"Создаем сервер БД"${NOCOLOR}

    sudo -u $CURRENT_USER $PGSQL_BIN"initdb" --pgdata=$DB_FOLDER --auth=trust --username=root --encoding=utf8 --lc-messages=C

    echo -e ${GREEN}"Правим строки"${NOCOLOR}
    sed -i 's/#port =.*/'"port = $PG_PORT               # (change requires restart)"'/' $DB_FOLDER/postgresql.conf
    sed -i 's/#log_min_messages =.*/log_min_messages = error\t\t# values in order of decreasing detail:/' $DB_FOLDER/postgresql.conf
    sed -i 's/#client_min_messages =.*/client_min_messages = error\t\t# values in order of decreasing detail:/' $DB_FOLDER/postgresql.conf
    sed -i 's\#unix_socket_directories =.*\'"unix_socket_directories = '/tmp'		# comma-separated list of directories"'\' $DB_FOLDER/postgresql.conf
    echo "Готово"
fi

echo -e ${GREEN}"Инициализация службы"${NOCOLOR}
if [ -f /etc/systemd/system/CredoRepositoryBackend.service ];
then
    systemctl is-active --quiet CredoRepositoryBackend.service && systemctl stop CredoRepositoryBackend.service
    rm -f /etc/systemd/system/CredoRepositoryBackend.service
fi

sed 's/User=.*/'"User=$CURRENT_USER"'/' /opt/CredoRepository/share/pg_service > /etc/systemd/system/CredoRepositoryBackend.service
sed -i 's\ExecStart=.*\'"ExecStart=${PGSQL_BIN}pg_ctl start -D \${PGDATA} -s -o \"-p \${PGPORT}\" -w -t 300"'\' /etc/systemd/system/CredoRepositoryBackend.service
sed -i 's\ExecStop=.*\'"ExecStop=${PGSQL_BIN}pg_ctl stop -D \${PGDATA} -s -m fast"'\' /etc/systemd/system/CredoRepositoryBackend.service
sed -i 's\ExecReload=.*\'"ExecReload=${PGSQL_BIN}pg_ctl reload -D \${PGDATA} -s"'\' /etc/systemd/system/CredoRepositoryBackend.service
sed -i 's/Environment=PGPORT=.*/'"Environment=PGPORT=$PG_PORT"'/' /etc/systemd/system/CredoRepositoryBackend.service
sed -i 's\Environment=PGDATA=.*\'"Environment=PGDATA=$DB_FOLDER"'\' /etc/systemd/system/CredoRepositoryBackend.service

echo -e ${GREEN}"Настраиваем конфиг"${NOCOLOR}
if [ $HAS_CONFIG = 0 ];
then
    sed 's/\[PG_PORT\]/'"$PG_PORT"'/' /opt/CredoRepository/share/config.xml > /opt/CredoRepository/share/config_new.xml
    sed -i 's/\[SERVER_NAME\]/'"$SERVER_NAME"'/' /opt/CredoRepository/share/config_new.xml
    sed -i 's/\[DB_NAME\]/'"crepodb"'/' /opt/CredoRepository/share/config_new.xml
    sed -i 's\<path>.*\'"<path>$REPO_FOLDER</path>"'\' /opt/CredoRepository/share/config_new.xml
    sed -i 's/\[SERVER_PORT\]/'"$SERVER_PORT"'/' /opt/CredoRepository/share/config_new.xml
    sed -i 's/\[SERVER_IFACE\]/'"$SERVER_IFACE"'/' /opt/CredoRepository/share/config_new.xml
    mkdir -p /home/$CURRENT_USER/.local/share/Credo-Dialogue/CredoRepository
    mv -f /opt/CredoRepository/share/config_new.xml /home/$CURRENT_USER/.local/share/Credo-Dialogue/CredoRepository/config.xml
    chown -R $CURRENT_USER: /home/$CURRENT_USER/.local/share/Credo-Dialogue
    sudo -u $CURRENT_USER /opt/CredoRepository/bin/set_root_pwd $PASS_ROOT
fi

systemctl daemon-reload
systemctl start CredoRepositoryBackend.service || Exit
systemctl enable CredoRepositoryBackend.service
systemctl --no-pager --full status CredoRepositoryBackend.service || Exit

sudo -u $CURRENT_USER $PGSQL_BIN"pg_ctl" status -D $DB_FOLDER || Exit

if ! $PGSQL_BIN"psql" -h localhost -p $PG_PORT -U root -w -d crepodb -c "" 2>&1;
then
    $PGSQL_BIN"psql" -h localhost -p "$PG_PORT" -U root -w -d postgres -c ""
    $PGSQL_BIN"psql" -h localhost -p $PG_PORT -U root -w -d postgres -c "create database crepodb"
    $PGSQL_BIN"psql" -h localhost -p $PG_PORT -U root -w -d crepodb -f /opt/CredoRepository/share/pg_create.sql
fi

chmod a+x /opt/CredoRepository/share/install_main_service
/opt/CredoRepository/share/install_main_service /opt/CredoRepository/bin/ $CURRENT_USER

echo -e ${GREEN}"Успешно!"${NOCOLOR}
read -n 1 -s -r -p "Нажмите любую клавишу...\n"
