#!/bin/bash

# Запуск 
#	update.sh - обновление до последней сборки
#	update.sh <set> - обновление до указанной сборки, номер сборки должен быть больше текущей

cd ${0%${0##*/}}.

if [ -e setenv.sh ]
then
    . ./setenv.sh
fi

INIT_D=/etc/init.d/
SYSTEMD=/etc/systemd/system/multi-user.target.wants/
SERVER=${SERVER:-'bgbilling'}
SCHEDULER=${SCHEDULER:-'bgscheduler'}
DATALOADER=/etc/init.d/bgdataloader
TEE=/usr/bin/tee
DATE=/bin/date

snapshot=`find ./snapshots -type f -mtime 0 | tail -1`

if [[ -z $snapshot ]]; then
    echo "Actual snapshot not found!"
    echo "Create snapshot..."
    ./snapshot.sh create
    snapshot=`find ./snapshots -type f -mtime 0 | tail -1`
fi

echo "Found actual snapshot: $snapshot"

time=`${DATE} +%d_%H:%M:%S`

if [ -e ${DATALOADER} ]; then
    echo "# Stopping DataLoader"
    ${DATALOADER} stop
fi

echo "# Stopping Scheduler"
if [ -e ${SYSTEMD}${SCHEDULER}.service ]
then
    systemctl stop ${SCHEDULER}.service
else
    ${INIT_D}${SCHEDULER} stop
fi

echo "# Stopping Server"
if [ -e ${SYSTEMD}${SERVER}.service ]
then
    systemctl stop ${SERVER}.service
else
    ${INIT_D}${SERVER} stop
fi

echo "# Start Updating"
./bg_installer.sh update $1 | ${TEE} ./log_update_${time}

echo "# Starting Server"
if [ -e ${SYSTEMD}${SERVER}.service ]
then
    systemctl start ${SERVER}.service
else
    ${INIT_D}${SERVER} start
fi

echo "# Starting Scheduler"
if [ -e ${SYSTEMD}${SCHEDULER}.service ]
then
    systemctl start ${SCHEDULER}.service
else
    ${INIT_D}${SCHEDULER} start
fi

if [ -e ${DATALOADER} ]; then
    echo "# Starting DataLoader"
    ${DATALOADER} start
fi

#if [ -e .bgclient_keystore_user -o -e .bgclient_keystore ]; then
#    ./bgclient_javawebstart.sh
#fi