#!/bin/sh

# User directory prepare
if [ ! -d ~/.openscada ]; then mkdir -m 700 ~/.openscada; fi
if [ ! -d ~/.openscada/ARCHIVES ]; then
    mkdir -pm 700 ~/.openscada/ARCHIVES/MESS;
    mkdir -pm 700 ~/.openscada/ARCHIVES/VAL;
fi
if [ ! -L ~/.openscada/icons ]; then ln -s /var/spool/openscada/icons ~/.openscada/icons; fi
if [ ! -d ~/.openscada/LibsDB ]; then cp -R /var/spool/openscada/LibsDB ~/.openscada/; fi
if [ ! -d ~/.openscada/DATA ]; then mkdir -m 700 ~/.openscada/DATA; fi
if [ ! -e ~/.openscada/oscada.xml ]; then cp /etc/oscada_start.xml ~/.openscada/oscada.xml; fi
cd ~/.openscada

# Program command and lock file
pCmd="openscada --CoreDumpAllow --Config=./oscada.xml"
pLock=".start.lock"

# Check for already started programm present
if [ -f $pLock ] && ps -Ao pid,command | grep "$(cat ${pLock})[ ]*${pCmd}" > /dev/null; then
    echo "OpenSCADA station already started!";
    exit 1;
fi

# Call programm
$pCmd $@ &
pPid=$!

# Create lock file
echo $pPid > $pLock

# Wait for programm stop
wait $pPid
echo "Program result: $?"

# Core dump files "core[.*]" into work directory process
if [ -n "$(which gdb 2> /dev/null)" ]; then
    cd ~/.openscada/
    for fit in `ls core* 2> /dev/null`; do
	echo "Core dump process for back trace purchase to file start_${fit}_$(date +%F_%H.%M).crash"
	gdb openscada --core ${fit} --batch --quiet -ex "thread apply all bt full" -ex "quit" > start_${fit}_$(date +%F_%H.%M).crash
	rm -f ${fit}
    done
fi

# Remove lock file
rm -f $pLock