#
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
#
INSTALL_PATH=$(cat /home/ICUser/RDInstalled.xml | grep installpath | awk -F "\"" '{print $2}')
CURRENT_PATH=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

function backup() {
	mkdir "$INSTALL_PATH"/Runtime@tmp
    cp -arf "$INSTALL_PATH"/Runtime/LegoRuntime/plugins/DRM-FusionShpere-OpenStack-Bundle-0.0.1-SNAPSHOT.jar "$INSTALL_PATH"/Runtime@tmp
}

function cleanBackup() {
    rm -rf "$INSTALL_PATH"/Runtime@tmp
}

function updateOpenstackBundle() {
    echo "Start to update openstack bundle..."
    echo y | cp "$CURRENT_PATH"/DRM-FusionShpere-OpenStack-Bundle-0.0.1-SNAPSHOT.jar "$INSTALL_PATH"/Runtime/LegoRuntime/plugins/
    echo "Update openstack bundle end."
}

function stopService() {
    echo "Start to shutdown system..."
    pushd "$INSTALL_PATH/Runtime/bin"  >/dev/null 2>&1 || return 1
    echo y | sh shutdownSystem.sh
    popd >/dev/null 2>&1 || return 1
    echo "Shutdown system success."
}

function startService() {
    echo "Start to start system..."
    pushd "$INSTALL_PATH/Runtime/bin"  >/dev/null 2>&1 || return 1
    sh startSystem.sh
}

function rollback() {
    rm -rf "$INSTALL_PATH"/Runtime/LegoRuntime/plugins/DRM-FusionShpere-OpenStack-Bundle-0.0.1-SNAPSHOT.jar
    cp -arf "$INSTALL_PATH"/Runtime@tmp/DRM-FusionShpere-OpenStack-Bundle-0.0.1-SNAPSHOT.jar "$INSTALL_PATH"/Runtime/LegoRuntime/plugins/
 
    cleanBackup
    startService
    echo "Rollback end."
    exit 1
}

function checkVersion() {
    local version=$(cat /home/ICUser/RDInstalled.xml | grep version | grep platform | awk -F "\"" '{print $4}')
    if [ "${version%%.*}" != "22" ];then
      echo "Not support version."
      exit 1
    fi
}

function main() {
    checkVersion
    stopService
    backup

    updateOpenstackBundle
    if [ $? != 0 ];then
      echo "Update openstack bundle. Rollback..."
      rollback
    fi

    startService
    if [ $? -ne 0 ];then
      echo "Start system failed. Rollback..."
      rollback
    else
      echo "Start system success."
    fi

    cleanBackup
    echo "Clipatch success."
}

main