#!/bin/bash

prog=$(basename "$0")
thisfile=$(readlink -f "$0")
thisdir=$(dirname "$thisfile")
HALFILE="$thisdir"/help.hal

# Don't care if cd succeeds. Just so user can use halcmd 'save' to create a file in $HOME
cd || true

function popup () {
  msg="$*"
  wish <<EOF &
  wm withdraw .
  tk_messageBox \
    -title "$prog" \
    -message "$msg" \
    -icon error \
    -type ok
  destroy .
EOF
} ;# popup


[ "$TERM" = "dumb" ] && TERM=xterm
[ -x "$(which "$COLORTERM")" ] && TERM=$COLORTERM
[ -z "$TERM" ] && TERM=xterm

# wip: xterm is well-behaved, some other terminals are not
# for now: force to xterm
TERM=xterm

REALTIME=$(linuxcnc_var REALTIME)
# make sure TERM uses the expected halrun (rip or install)
HALRUN=$(which halrun)

if [ -n "$debug" ] ; then
  echo "COLORTERM=$COLORTERM"
  echo "TERM=$TERM"
  echo "HALRUN=$HALRUN"
  echo "REALTIME=$REALTIME"
fi

if $REALTIME status >/dev/null ; then
  msg="$prog: LinuxCNC is active"
  echo "$msg"
  popup "$msg"
  exit 1
fi


# terminate any other halrun instance:
$HALRUN -U >/dev/null 2>&1

if [ "$TERM" = "xterm" ] ; then
  $TERM -geometry 80x40 \
        -sb \
        -fg black -bg ivory2 \
        -title "halrun (Use Ctrl-L-button, Ctrl_R-button for xterm options)" \
        -e "echo Working_Directory=$(pwd);echo; $HALRUN -I $HALFILE"
else
  $TERM -e "$HALRUN -I $HALFILE"
fi

# cleanup
halrun -U >/dev/null 2>&1
exit 0
