#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
FISCALWIRE_DIR=$(dirname "$DIR")
POSCONNECT_DIR=$FISCALWIRE_DIR/posconnect
DATESTR=$(date +%Y_%m_%d_%H_%M_%S)
ARCH=$(uname -m)

# verific arhitectura sistemului
if [ $ARCH == "i686" ] ; then
    POSCONNECT_SERVER=$DIR/posconnect_LINUX_x86
else
    if [ $ARCH == "x86_64" ] ; then
        POSCONNECT_SERVER=$DIR/posconnect_LINUX_amd64
    else
        POSCONNECT_SERVER=$DIR/posconnect_LINUX_arm
    fi
fi

if [ ! -d "$POSCONNECT_DIR" ]; then
    mkdir -p "$POSCONNECT_DIR"
fi

if [ ! -f "$POSCONNECT_DIR"/smartpayment.json ]; then
    cp "$DIR"/smartpayment.json "$POSCONNECT_DIR"/
fi

# dau drepturi de executie
chmod +x "$POSCONNECT_SERVER"

# verific daca e deja pornit posconnect si il inchid
pid=$(ps -ax | grep "[p]osconnect_" | awk '{print $1}')
if [ ! -z "$pid" ]; then
    kill -15 $pid
    sleep 1
    kill -9 $pid
fi

cd "$POSCONNECT_DIR"

if [ ! -d "$POSCONNECT_DIR"/logs/$DATESTR ]; then
    mkdir -p "$POSCONNECT_DIR"/logs/$DATESTR
fi

mv "$POSCONNECT_DIR"/*log "$POSCONNECT_DIR"/logs/$DATESTR/

# pornesc posconnect server
nohup "$POSCONNECT_SERVER" -debug >> "$FISCALWIRE_DIR"/fiscalwire.log &

exit 0
