#!/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~~~~~~
###

# первый параметр номер версии
# если задан второй параметр чистит конфиги

DIRNAME="$( cd "$(dirname "$0")" ; pwd -P )"
ESB_ENTAXY_VERSION=$1
PATCH_FILE=$DIRNAME/karaf_update_$ESB_ENTAXY_VERSION.tgz

if test -f "$PATCH_FILE"; then
  echo "Installing $ESB_ENTAXY_VERSION, use patch file: $PATCH_FILE"
else
  echo "Error: patch file $PATCH_FILE not found"
fi

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
sudo cp -r /opt/karaf/etc $BKPDIR
sudo cp -r /opt/karaf/data $BKPDIR

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

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

sudo tar -zxk -f $PATCH_FILE -C /opt/karaf/

if [ -n "$2" ]
then
  sudo /opt/karaf/etc/change_ips.sh
  echo "Run change_ips.sh"
fi

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

sudo systemctl start karaf
echo "Started karaf"

sleep 30
sudo su - -c "/opt/karaf/bin/client 'list --no-format | grep -v Active'" karaf
