 #!/bin/bash
 
function secureNeeded()
{
if [ "$XDG_CURRENT_DESKTOP" = "" ]
then
  desktop=$(echo "$XDG_DATA_DIRS" | sed 's/.*\(xfce\|kde\|gnome\).*/\1/')
else
  desktop=$XDG_CURRENT_DESKTOP
fi

desktop=${desktop,,}  # convert to lower case
echo "use desktop $desktop"
if [ "$desktop" == "gnome" ];
      then
      return 1
fi
if [ "$desktop" == "unity" ];
      then
      return 1
fi
if [ "$desktop" == "kde" ];
      then
      return 1
fi
   return 0
}

 DIR="$( cd "$( dirname "$0" )" && pwd )"
 
 BASE=$DIR
 FILE="layout"

 if [ -f "$DIR/bin/layout" ]; then
     BASE=$DIR
     FILE=$DIR"/bin/layout"
 else 
     if [ -f "/opt/layout/bin/layout" ]; then
          BASE="/opt/layout"
          FILE="/opt/layout/bin/layout"
     else
          echo "executable not found"
          exit 1
     fi
 fi
 
 echo "LayoutEditor installed at $BASE"
 
 if [ -d $BASE"/lib" ]; then
   # extra libraries
   export LD_LIBRARY_PATH=$BASE/lib:$LD_LIBRARY_PATH
 fi
 
 export PYTHONPATH=$BASE/python:$PYTHONPATH

 # OpenAccess
 OAVER=""
 if [ -L $BASE"/oa" ]; then
   if [ -f "$BASE/oa/bin/oaGetVersion" ]; then
      echo "OpenAccess libraries found at $BASE/oa"
   else
      echo "oaGetVersion not found"
      echo "fall back to oauniversal"
      if secureNeeded
      then
           $FILE --secure $*
      else
           $FILE $*
      fi
      exit 0
   fi

   SYSNAME=$($BASE/oa/bin/sysname)
   export OA_SYSNAME=$SYSNAME
   if [ "$SYSNAME" == "unknown" ]; then
      SYSNAME=$(ls $BASE/oa/bin|grep linux_*)
      SYSNAME=${SYSNAME%_64}
      SYSNAME=${SYSNAME%_32}
      export OA_SYSNAME=$SYSNAME
   fi

   OAVER=$($BASE/oa/bin/oaGetVersion 2> /dev/null |grep oaBase | sed 's/.*oaBase\(.*\)\..*/\1/' | sed 's/[[:blank:]]//g')
   echo "use OpenAccess version $OAVER"
   machine=`uname -m`
   case $machine in
	*86_64 )
	  bit=64 ;;
	*86  )
	  bit=32 ;;
        * ) 
          bit=32 ;;
   esac 
   LIBPATH=$($BASE/oa/bin/oaGetLibPath -numBits $bit)
   export LD_LIBRARY_PATH=$LIBPATH:$BASE/python/oa/lib:$LD_LIBRARY_PATH
   export OA_PLUGIN_PATH=$BASE/oa/data/plugins

   # start LayoutEditor with OpenAccess version $OAVER
   if secureNeeded
   then
        $FILE --secure --oa$OAVER $*
   else
        $FILE --oa$OAVER $*
   fi

 else 
   echo "OpenAccess not found. Add a link to the oa binaries folder at layout/oa to use OpenAccess"
   # start LayoutEditor without OpenAccess or with  universal plugin
   if secureNeeded
   then
        $FILE --secure $*
   else
        $FILE $*
   fi
   
 fi
 

