#!/bin/bash

export DISPLAY=:0.0

UPDATE_LOG="./logs/back/app/update.log"

CURR_DIR=$(pwd)

UPDATE_INSTALL_DIR="./"
APP_UPDATE="update/app"
APP_UPDATE_FILES="${APP_UPDATE}/content/"
APP_REDUNDANT_LIST="${APP_UPDATE}/.remove"

RES_UPDATE="update/res"
RES_UPDATE_FILES="${RES_UPDATE}/content/"

while true; do
    ./bin/trigger/app-before-start.sh

    PARAMS=""
    # файл со специальными опциями java
    OPT_LOCAL=bin/java-local.options
    # файл со базовыми опциями электрон
    OPT_ORIGIN=bin/java-origin.options

    if [[ -f "$OPT_LOCAL" ]]; then
      PARAMS=$(cat $OPT_LOCAL)
    elif [[ -f "$OPT_ORIGIN" ]]; then
      PARAMS=$(cat $OPT_ORIGIN)
    fi

    /usr/bin/java -Dsun.security.smartcardio.library=/usr/lib64/libpcsclite.so.1 $PARAMS -cp app/back/*:app/back/libs/*  pro.smartix.daemon.app.Runner
    retval=$(cat .app.exitcode)
    echo "bash: process exit with code: ${retval}"
    ./bin/trigger/app-after-stop.sh

    if [[ "${retval}" == "0" ]]; then
        echo "Software restart (0)"
    elif [[ "${retval}" == "1" ]]; then
        echo "Stop software"
        break
    elif [[ "${retval}" == "2" ]]; then
        echo "Reboot PC"
        sudo /sbin/reboot
        break
    elif [[ "${retval}" == "3" ]]; then
        echo "Power off PC"
        sudo /sbin/poweroff
        break
    elif [[ "${retval}" == "10" ]]; then
        ./bin/trigger/app-before-update.sh
        echo "bash: start update application from: $(pwd)" >> ${UPDATE_LOG}
        rsync -av --remove-source-files ${APP_UPDATE_FILES} ${UPDATE_INSTALL_DIR} >> ${UPDATE_LOG} 2>&1
        find app/bin/ -type f | xargs chmod 755
        if [[ -f ${APP_REDUNDANT_LIST} ]]; then
            for files in $(echo $(cat ${APP_REDUNDANT_LIST} ) ); do
                echo "try to delete files: ${rmline} " >> ${UPDATE_LOG} 2>&1
                rm -f $files 1>/dev/null 2>&1
            done
            rm -f ${APP_REDUNDANT_LIST} >> ${UPDATE_LOG} 2>&1
        fi
        /usr/bin/killall electron
        /usr/bin/chmod +x ./bin/*.sh
        /usr/bin/chmod +x ./bin/trigger/*.sh
        /usr/bin/gunzip -f -k ./app/front/*.asar.gz
        ./bin/trigger/app-after-update.sh
        break
    elif [[ "${retval}" == "11" ]]; then
        echo "bash: start update resources"
        rsync -av --remove-source-files ${RES_UPDATE_FILES} ${UPDATE_INSTALL_DIR} >> ${UPDATE_LOG} 2>&1
    else
        echo "Unknown exit code ${retval}"
    fi
done

