#!/bin/bash
# A little shell script to start MorphoGraphX with a shell window underneath
#
# For nVidia optimus cards on laptops, MorphoGraphX needs to called with optirun

# First, give the option for the user to specify whatever OPTIRUN is

test_nvidia_context() {
  if [ $($1 glxinfo 2>/dev/null | grep -c -e 'direct rendering: Yes' -e 'OpenGL vendor string.*NVIDIA') -eq 2 ]; then
    echo $1
    return 0
  fi
  return 1
}

test_context() {
  if [ $($1 glxinfo 2>/dev/null | grep -c -e 'direct rendering: Yes' -e 'OpenGL vendor string') -ge 2 ]; then
    echo $1
    return 0
  fi
  return 1
}

test_nvidia_command() {
  CMD=$1
  if REAL_CMD=$(which $CMD); then
    test_nvidia_context $REAL_CMD
    return 0
  fi
  return 1
}

test_command() {
  CMD=$1
  if REAL_CMD=$(which $CMD); then
    test_context $REAL_CMD
    return 0
  fi
  return 1
}

test_commands() {
  # Testing if the current context is simply sufficient
  if test_nvidia_context; then
    echo
    return 0
  fi
  # Try to find utilities to find an nvidia context
  for cmd in primusrun optirun vglrun; do
    if OPTIRUN=$(test_nvidia_command $cmd); then
      echo $OPTIRUN
      return 0
    fi
  done
  # Test for non nvidia context, in case
  if test_context; then
    echo
    return 0
  fi
  echo
  return 1
}

if [ -z "$OPTIRUN" ]; then
  if ! OPTIRUN=$(test_commands); then
    echo "Warning, cannot find a good OpenGL display. Trying default display."
  fi
fi

echo "MorphoGraphX command line: \"${OPTIRUN} MorphoGraphX '$1'\""

x-terminal-emulator -e "bash -ilc \"${OPTIRUN} MorphoGraphX '$1'; sleep 30\""
