#!/bin/bash

set +e
need_reboot=
mem_size=$(free -m | sed '2!d' | sed 's/  */ /g' | cut -d' ' -f2)

res=$(cat /etc/group | grep 'aisexpert')
if [ -z "$res" ]; then
    addgroup aisexpert
fi

res=$(groups $SUDO_USER | grep 'aisexpert')
if [ -z "$res" ]; then
    adduser $SUDO_USER aisexpert
    need_reboot=yes
fi

if [ "$need_reboot" = "yes" ]; then
    echo "The user $SUDO_USER added to the aisexpert group. Need reboot computer"
fi

chown -R root:aisexpert /etc/aisexpert
chown -R root:aisexpert /var/opt/aisexpert
chmod -R ug=rwX,o=rX    /var/opt/aisexpert

gbak=/opt/firebird/bin/gbak
db_dir=/var/opt/aisexpert/database

if [ -x $gbak ]; then
    rm -f $db_dir/aisexpert-empty.fdb

    # Создание пустой БД
    $gbak -c $db_dir/aisexpert-empty.fbk $db_dir/aisexpert-empty.fdb
    chown :firebird $db_dir/aisexpert-empty.fdb

    # Обнолвение хранимой процедуры возвращающей версию БД
    sudo /opt/firebird/bin/isql -q -u SYSDBA -p masterkey $db_dir/aisexpert-empty.fdb <<-EOF
	SET TERM ^ ;
	create or alter procedure "VERSION"
	returns (DB_VERSION integer)
	as
	begin
	  :DB_VERSION = %DB_VERSION%;
	  suspend;
	end
	^
	SET TERM ; ^
	GRANT EXECUTE ON PROCEDURE "VERSION" TO SYSDBA;
	EOF
fi

for f in $(ls /var/opt/aisexpert/database/aisexpert*.fdb); do
    chown :firebird $f
    chmod ug=rw,o=r $f
done

EMULATION_MODE=
read -p "Select UsersPool service work mode (use emulation - E; use LDAP - L) [E/l]: " EMULATION_MODE
EMULATION_MODE=${EMULATION_MODE:-'E'}
if [[ $EMULATION_MODE =~ ^(e|E)$ ]]; then
    EMULATION_MODE="-e"
    echo "UsersPool service will work in emulation mode"
else
    EMULATION_MODE=''
    echo "UsersPool service will work in LDAP mode"
fi

sed -e "s/%TARGET_USER%/$SUDO_USER/" \
    -i /etc/systemd/system/aisexpert.service

sed -e "s/%TARGET_USER%/$SUDO_USER/" \
    -e "s/%EMULATION_MODE%/$EMULATION_MODE/" \
    -i /etc/systemd/system/userspool.service

systemctl daemon-reload

function firebird_conf_modify()
{
    local param=$1
    local value=$2
    sed -e "s/#${param} *=/${param} =/; s/^${param} *=.*/${param} = ${value}/" \
        -i /opt/firebird/firebird.conf
}

res=$(cat /opt/firebird/firebird.conf | grep 'AIS EXPERT MOD')
if [ -z "$res" ]; then
    # Конфигурируем firebird-сервер
    cp -f /opt/firebird/firebird.conf /opt/firebird/firebird.conf.ais.bak

    # Добавляем маркер в conf-файл, в первую строку
    sed -e '1 s/^/############ AIS EXPERT MOD #############\n/' \
        -i /opt/firebird/firebird.conf

    default_db_cache_pages=1024000 # Для 64 Гб
    database_growth_increment=102400000 # Для 64 Гб
    file_system_cache_threshold=2048000
    temp_cache_limit=4096000000

    # Модифицируем параметры
    if [ "$mem_size" -gt 64000 ]; then
        default_db_cache_pages=$(($default_db_cache_pages / 1))  # 64 Гб
        database_growth_increment=$(($database_growth_increment / 1))
        file_system_cache_threshold=$(($file_system_cache_threshold / 1))
        temp_cache_limit=$(($temp_cache_limit / 1))
    elif [ "$mem_size" -gt 32000 ]; then
        default_db_cache_pages=$(($default_db_cache_pages / 2))  # 32 Гб
        database_growth_increment=$(($database_growth_increment / 2))
        file_system_cache_threshold=$(($file_system_cache_threshold / 2))
        temp_cache_limit=$(($temp_cache_limit / 2))
    elif [ "$mem_size" -gt 15500 ]; then
        default_db_cache_pages=$(($default_db_cache_pages / 4))  # 16 Гб
        database_growth_increment=$(($database_growth_increment / 4))
        file_system_cache_threshold=$(($file_system_cache_threshold / 4))
        temp_cache_limit=$(($temp_cache_limit / 4))
    else
        default_db_cache_pages=$(($default_db_cache_pages / 8))  # меньше 16 Гб
        database_growth_increment=$(($database_growth_increment / 8))
        file_system_cache_threshold=$(($file_system_cache_threshold / 8))
        temp_cache_limit=$(($temp_cache_limit / 8))
    fi

    firebird_conf_modify DefaultDbCachePages       $default_db_cache_pages
    firebird_conf_modify DatabaseGrowthIncrement   $database_growth_increment
    firebird_conf_modify FileSystemCacheThreshold  $file_system_cache_threshold
    firebird_conf_modify FileSystemCacheSize       30
    firebird_conf_modify TempBlockSize             2M
    firebird_conf_modify TempCacheLimit            $temp_cache_limit
    firebird_conf_modify WireCrypt                 Disabled
    firebird_conf_modify WireCompression           false
    firebird_conf_modify LockMemSize               200M
    firebird_conf_modify ServerMode                Super
    firebird_conf_modify Providers                 Engine12,Loopback,Remote
fi

#systemctl restart firebird-superserver.service
#sleep 2

systemctl unmask userspool.service
systemctl enable userspool.service

if [ "$EMULATION_MODE" != "-e" ]; then
    read -r -p "Start the userspools service (LDAP variant) after installation complete [Y/n] " resp;
    resp=${resp:-'Y'}
    if [[ $resp =~ ^(y|Y)$ ]]; then
        systemctl start userspool.service
    fi
else
    systemctl start userspool.service
fi

sleep 1

systemctl unmask aisexpert.service
systemctl enable aisexpert.service
systemctl start  aisexpert.service

systemctl unmask aisexpert-notify.service
#systemctl enable aisexpert-notify.service

exit 0
