#!/bin/sh

###
# ~~~~~~licensing~~~~~~
# karaf-features
# ==========
# Copyright (C) 2020 - 2021 EmDev LLC
# ==========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ~~~~~~/licensing~~~~~~
###

# берет номер версии из файла version, если его нет то используется 1.8
# если задан первый параметр чистит конфиги

DIRNAME="$( cd "$(dirname "$0")" ; pwd -P )"

if test -f "$DIRNAME/version"; then
    ESB_ENTAXY_VERSION=`cat $DIRNAME/version`
else
    ESB_ENTAXY_VERSION=1.8
fi
echo "Installing $ESB_ENTAXY_VERSION"

sudo systemctl stop karaf

echo "Stopped karaf"

BKPDIR=$DIRNAME/backup-karaf-$(date +%d%m%Y-%H%M)
mkdir -p $BKPDIR

echo "Created dir $BKPDIR"

# create backup
cp -r /opt/karaf/etc $BKPDIR
cp -r /opt/karaf/data $BKPDIR

# clean backed dirs
sudo rm -rf /opt/karaf/data/*

if [ -n "$1" ]
then
  # clean configs
  sudo rm -rf /opt/karaf/etc/ru.entaxy.esb.*
  sudo rm -rf /opt/karaf/etc/org.ops4j.datasource-entaxy.esb.*
  echo "Karaf data and configs cleaned up"
else
  echo "Karaf data cleaned up"
fi

# restore file owner
sudo chown -R karaf. /opt/karaf/{etc,data}

sudo systemctl start karaf

echo "Started karaf"

sleep 15

sudo cp -r $DIRNAME/install.karaf /opt/karaf/

sudo su - -c "/opt/karaf/bin/client 'esb_entaxy_VERSION=$ESB_ENTAXY_VERSION; shell:source /opt/karaf/install.karaf;'" karaf

echo "== Update database"
sudo su - -c "/opt/karaf/bin/client 'feature:install liquibase-updater'" karaf
sleep 60
echo "== Install all features"
sudo su - -c "/opt/karaf/bin/client 'feature:install entaxy-all'" karaf
sleep 60
echo "== Install system-group profile"
sudo su - -c "/opt/karaf/bin/client 'bundle:install -s blueprint:mvn:ru.entaxy.esb.integration.esb.test.profiles/test-profiles/$ESB_ENTAXY_VERSION/xml/g_test'" karaf

echo "Install process finished"
