#!/bin/bash
# AQ
# 20161103

logger -t soft-logic "Start configurator"

DN=$(dirname "$0")
CLASSPATH=$DN
PORTBLACKLIST=""
PARAMS=""
for port in `ls /dev/ttyACM* /dev/ttyUSB* 2>/dev/null`; do
        if grep -q ${port} $DN/configuration.xml; then
            portname=`echo ${port} | sed "s/\/dev\///"`
            skiplink=`ls -l /dev/serial/by-id/ | grep $portname | awk '{print $9}'| sed "s/^/\/dev\/serial\/by-id\//"`
            if [ ! -z ${skiplink} ]; then
                PORTBLACKLIST="${skiplink},${PORTBLACKLIST}"
            fi
        else
            if [ ! -z ${port} ]; then
                PORTBLACKLIST="${port},${PORTBLACKLIST}"
            fi
        fi
done

if [ ! -z "${PORTBLACKLIST}" ]; then
    PARAMS=`echo "-Dport.deny=${PORTBLACKLIST::-1}"`
fi

for jar in $(ls $DN/{lib,ext,ext/drivers}/*.jar); do CLASSPATH=$CLASSPATH:$jar; done
if [ -f $DN/local.properties ]; then
    for line in `cat $DN/local.properties`
    do
        if [ "x$line" != "x" ];then
	    linetr=`echo $line | sed 's/\r$//'`
            PARAMS="-D$linetr $PARAMS"
        fi
    done
fi

if [ -f $DN/config.properties ]; then
    for line in `cat $DN/config.properties`
    do
        if [ "x$line" != "x" ];then
	    linetr=`echo $line | sed 's/\r$//'`
            PARAMS="-D$linetr $PARAMS"
        fi
    done
fi
java -cp $CLASSPATH -Djava.library.path=$DN/jni -Dterminal.dir=$DN $PARAMS -Xmx256m ru.softlogic.configurator.Appication
