#!/bin/bash

shopt -s expand_aliases

if [ -n "$(which gettext 2> /dev/null)" ]; then
    alias GETTEXT=gettext
else
    alias GETTEXT=echo
fi
export TEXTDOMAIN=openscada
export TEXTDOMAINDIR=/usr/share/locale
if [ -n "$(which tput)" ]; then tput init; TERM_REZ=$?;
elif [ "x$TERM" = "xxterm" ]; then TERM_REZ=0;
else TERM_REZ=1; fi
tmpfile=`mktemp -t oscada_XXXXXX`

StartOrigCfgPref=/usr/etc
StartOrigCfgFile=$StartOrigCfgPref/oscada_start.xml
StartWorkDir=/usr/share/openscada
WorkDir=$StartWorkDir
DESKTOP_DIR=
if [ -n "$(which xdg-user-dir)" ] && [ -n "$(xdg-user-dir DESKTOP)" ]; then DESKTOP_DIR="$(xdg-user-dir DESKTOP)"; fi

# Get the project name from first argument
ProjName=`echo $1 | sed -n "/--ProjName=\(.*\)/s//\1/p"`
# Get the project name from filename openscada_{ProjName}
if test "x$ProjName" = "x"; then ProjName=`echo $0 | sed -n "/.*openscada_\(.*\)/s//\1/p"`; else shift; fi
# Get the project name from variable "OSCADA_ProjName"
if test "x$ProjName" = "x" -o "$ProjName" = "start"; then ProjName=$OSCADA_ProjName; fi
# Set the project name to default "start"
if test "x$ProjName" = "x" -o "$ProjName" = "start"; then
    if test $TERM_REZ = 0 -a -n "$(which dialog)" || test -n "$DISPLAY" -a -n "$(which kdialog || which zenity || which Xdialog)"; then
	prjList=("start" "<$(GETTEXT "Default")>" "<new>" "<$(GETTEXT "New project")>")
	if test ! -w $WorkDir/$ProjName; then
	    prjList=("${prjList[@]}" "<*>" "=== $(GETTEXT "User directory copy projects") ===")
	    for fit in `ls ~/.openscada`; do
		if test -d ~/.openscada/$fit && test -f ~/.openscada/$fit/oscada.xml; then prjList=("${prjList[@]}" "$fit" "$fit"); fi
	    done
	    prjList=("${prjList[@]}" "<*>" "=== $(GETTEXT "Pre-installed projects") ===")
	fi
	# Projects list obtaine from preinstalled projects
	for fit in `ls $StartWorkDir`; do
	    if test -d $StartWorkDir/$fit && test -f $StartOrigCfgPref/oscada_$fit.xml -o -f $StartWorkDir/$fit/oscada.xml; then prjList=("${prjList[@]}" "$fit" "$fit"); fi
	done

	rez=
	if test $TERM_REZ = 0 -a -n "$(which dialog)"; then dialog --menu "$(GETTEXT "Select project for start.")" 20 60 20 "${prjList[@]}" 2> $tmpfile; rez=`cat $tmpfile`;
	elif test -n "$(which kdialog)"; then rez=`kdialog --title "$(GETTEXT "OpenSCADA start")" --menu "$(GETTEXT "Select project for start.")" "${prjList[@]}"`;
	elif test -n "$(which zenity)"; then rez=`zenity --height=400 --width=300 --title "$(GETTEXT "OpenSCADA start")" --list --text="$(GETTEXT "Select project for start.")" --column="Tag" --column="Project" --hide-column=1 "${prjList[@]}" | cut -d"|" -f1`;
	elif test -n "$(which Xdialog)"; then Xdialog --title "$(GETTEXT "OpenSCADA start")" --no-tags --menubox "$(GETTEXT "Select project for start.")" 20 50 20 "${prjList[@]}" 2> $tmpfile; rez=`cat $tmpfile`; fi
	ProjName=$rez
	if test "x$ProjName" = "x" -o "x$ProjName" = "x<*>"; then ProjName=;
	# New project create
	elif test "x$ProjName" = "x<new>"; then
	    rez=
	    if test $TERM_REZ = 0 -a -n "$(which dialog)"; then dialog --inputbox "$(GETTEXT "Enter new project ID. Do not use spaces!")" 10 50 2> $tmpfile; rez=`cat $tmpfile`;
	    elif test -n "$(which kdialog)"; then rez=`kdialog --title "$(GETTEXT "OpenSCADA start")" --inputbox "$(GETTEXT "Enter new project ID. Do not use spaces!")" 'NewProject'`;
	    elif test -n "$(which zenity)"; then rez=`zenity --title "$(GETTEXT "OpenSCADA start")" --entry --text "$(GETTEXT "Enter new project ID. Do not use spaces!")" --entry-text="NewProject"`;
	    elif test -n "$(which Xdialog)"; then Xdialog --title "$(GETTEXT "OpenSCADA start")" --inputbox "$(GETTEXT "Enter new project ID. Do not use spaces!")" 10 50 2> $tmpfile; rez=`cat $tmpfile`; fi
	    ProjName=$rez
	    if test "x$ProjName" = "x"; then ProjName=;
	    # Move and prepare start ico to desktop
	    elif [ -n "$DESKTOP_DIR" ] && [ ! -f "$DESKTOP_DIR/openscada_$ProjName.desktop" ]; then
		cp /usr/share/applications/openscada.desktop "$DESKTOP_DIR/openscada_$ProjName.desktop";
		sed -i "s/Exec=/Exec=env OSCADA_ProjName=$ProjName /" "$DESKTOP_DIR/openscada_$ProjName.desktop"
		sed -i "s/\(^\(Generic\|\)Name\(=\|\\[.*\\]=\).*\)/\1: $ProjName/" "$DESKTOP_DIR/openscada_$ProjName.desktop"
	    fi
	fi
    else ProjName=start; fi
fi

rm -f $tmpfile

if [ -z "$ProjName" ]; then echo "$(GETTEXT "No a project set!")"; exit 1; fi

echo "$(GETTEXT "Set the project name to:") \"$ProjName\""

# Work directory check and prepare
StartCfgFile=$StartOrigCfgPref/oscada_$ProjName.xml
CfgFile=$StartCfgFile

## Check for work directory moving to user's home directory "~/.openscada" needs
if test -w $WorkDir -a ! -d $WorkDir/$ProjName; then mkdir -p $WorkDir/$ProjName; fi
if test ! -w $WorkDir/$ProjName; then
    WorkDir=~/.openscada
    if test ! -d $WorkDir/$ProjName; then
	mkdir -pm 700 $WorkDir/$ProjName;
	if test -d $StartWorkDir/$ProjName; then cp -R $StartWorkDir/$ProjName/* $WorkDir/$ProjName; fi
    fi
    CfgFile=$WorkDir/$ProjName/oscada.xml
    if test ! -e $CfgFile -a -f $StartCfgFile; then cp $StartCfgFile $CfgFile; fi
fi
if test -f $WorkDir/$ProjName/oscada.xml; then CfgFile=$WorkDir/$ProjName/oscada.xml; fi
if test ! -e $CfgFile -a -f $StartOrigCfgFile; then cp $StartOrigCfgFile $CfgFile; fi
## Check for local copy need for libraries DBs directory
if test -d $StartWorkDir/LibsDB -a ! -d $WorkDir/LibsDB; then cp -R $StartWorkDir/LibsDB $WorkDir; fi
if test ! -d $WorkDir/$ProjName/LibsDB -a ! -L $WorkDir/$ProjName/LibsDB; then ln -s ../LibsDB $WorkDir/$ProjName/LibsDB; fi
## Check for typical archives directory creation need
if test ! -d $WorkDir/$ProjName/ARCHIVES/MESS; then mkdir -pm 700 $WorkDir/$ProjName/ARCHIVES/MESS; fi
if test ! -d $WorkDir/$ProjName/ARCHIVES/VAL; then mkdir -pm 700 $WorkDir/$ProjName/ARCHIVES/VAL; fi

cd $WorkDir/$ProjName

# Programm command and lock file
pCmd="/usr/bin/openscada --CoreDumpAllow --Config=$CfgFile --StatName=$ProjName"
#pLock=".openscada.lock"

# Possible need using "flock" for race condition prevent
# Check for already started programm present
started=0
if ps -C $TEXTDOMAIN -o command | grep "^${pCmd}" > /dev/null; then started=1; fi
if test -f lock; then
    pid=`cat lock | sed -r 's/^0*([0-9]+).*/\1/'`
    if ps -A -o "pid cmd" | grep "^ *$pid.*openscada" > /dev/null; then started=1; fi
fi
if test $started = 1; then
    echo "OpenSCADA station \"$ProjName\" already started!";
    if test $TERM_REZ = 0 -a -n "$(which dialog)"; then dialog --msgbox "\"$ProjName\" $(GETTEXT "already started.")" 10 30;
    elif test -n "$(which kdialog)"; then kdialog --title "$(GETTEXT "OpenSCADA start")" --msgbox "\"$ProjName\" $(GETTEXT "already started.")";
    elif test -n "$(which zenity)"; then zenity --title "$(GETTEXT "OpenSCADA start")" --info --text="\"$ProjName\" $(GETTEXT "already started.")";
    elif test -n "$(which Xdialog)"; then Xdialog --title "$(GETTEXT "OpenSCADA start")" --msgbox "\"$ProjName\" $(GETTEXT "already started.")" 10 30; fi
    exit 1;
fi

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

# Create lock file
#echo $pPid > $pLock

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

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

# Remove lock file
#rm -f $pLock
