#!/bin/bash

#
# Обновление версии Базы Данных
#

if [ "$#" -ne 1 ]; then
    echo "Check parameters"
    exit 0
fi

set -e

database_file=$1

current_version=$(
/opt/firebird/bin/isql -pag 1000 -b -m -m2 -u SYSDBA -p masterkey $database_file << EOF
set heading off; SELECT DB_VERSION FROM VERSION;
EOF
)

current_version=`echo $current_version | sed -e 's/^[ \t]*//'`

echo "Current Database version is: "$current_version

new_version=$((current_version+1))

echo "---"
echo "Begin database version upgrade..."

sudo systemctl stop aisexpert
sudo systemctl stop firebird-superserver

VERSION=$(
/opt/firebird/bin/isql -pag 1000 -b -m -m2 -u SYSDBA -p masterkey $database_file << EOF
set heading off; SELECT DB_VERSION FROM VERSION;
EOF
)
echo "Current database version is: "$VERSION

echo "Update databse from "$current_version" to "$new_version

if [ $VERSION -ne $current_version ]; then
    echo "Check current version for db and script"
    exit 0
fi

FILE=version_"$current_version"_to_"$new_version".sql

echo "Apply script: "$FILE

if [ ! -f "$FILE" ]; then
    echo $FILE" already updated"
    exit 0
fi

update_command="sudo /opt/firebird/bin/isql -i $FILE -u SYSDBA -p masterkey $database_file"
echo $update_command
eval $update_command

sudo systemctl start firebird-superserver
sudo systemctl start aisexpert

echo "End database version upgrade"
