#!/bin/bash -x

HOME=/home/smartix
#определяем папку где лежит ПО, на новых образах есть machine, для старых образов определяем postamat или registrator
if [[ -d "$HOME"/machine ]]
then
    DIR=machine
elif [[ -d "$HOME"/postamat ]] 
then
    DIR=postamat
elif [[ -d "$HOME"/registrator ]] 
then
    DIR=registrator
fi

CONN=/home/smartix/$DIR/conf/connector.properties
EZ=electron.zip
EV=electron.version
ED=$HOME/electron

# строит путь к каталогу с electron
AP="os/linux/unk/"
function elpath {
    ARCH=$(arch)
    if [ $ARCH == "x86_64" ]; then
        AP="os/linux/x64/"
    elif [ $ARCH == "armv7l" ]; then
        AP="os/linux/arm32/"
    fi
}

# Проверяет необходимость обновления electron
function elupdate {
    elpath
    if [ -f "$AP/$EZ" ]; then
        if [ -f "$AP/$EV" ]; then
            if ! cmp -s $ED/$EV $AP/$EV; then
                rm -Rf $ED/*
                cp $AP/* $ED/
                unzip $ED/electron.zip -d $ED/
            else
                echo "Electron update is not required"
            fi
        else
            echo "File $AP/$EV is not exist. Skip update"
        fi
    else
        echo "File $AP/$EZ is not exist. Skip update"
    fi
}
elupdate

type_app=$(cat /home/smartix/$DIR/data/refs/point.json 2>/dev/null | (grep pointType || echo 100) | sed s/[^0-9]//g)
echo $type_app
ff=$(ls -l /home/smartix/$DIR/app/front/*.asar | grep -v "activator.asar" | head -1 | sed -r 's/^.+\///')
if [[ $type_app == '4' ]] || [[ $type_app == '6' ]]
    then app=postamat.asar
elif [[ $type_app == '1' ]]
    then app=registrator.asar
elif [[ $type_app == "100" ]]
   then app=$ff
fi

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

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

if [ -n "$(cat $CONN | grep -E 'apiKey.{5,}')" ]; then
    echo  "Api key is exist"
    cd /home/smartix/$DIR
    $ED/electron $PARAMS $HOME/$DIR/app/front/$app
else
    cd /home/smartix/$DIR
    $ED/electron $PARAMS $HOME/$DIR/app/front/activator.asar
    CODE=$?
    if [[ $CODE == '6' ]]; then
        cd /home/smartix/$DIR
        sudo systemctl restart smartixd
        sleep 30
        $ED/electron $PARAMS $HOME/$DIR/app/front/$app
    else
        echo "Restart Software"
    fi
fi
