#!/bin/bash

# Nautilus 'action' script.
# Place this (executable) file ~/.local/share/nautilus/scripts
# to have a 'send-to-mwp' option

function to_mwp {
  local fn="$1"

  mwp=
  # Invoke mwp if not running ...
  until dbus-send --session --print-reply=literal --dest=org.mwptools.mwp \
		  /org/mwptools/mwp \
		  org.freedesktop.DBus.Peer.Ping
  do
    if [ -z $mwp ] ; then
      mwp &
      mwp=$!
    fi
    sleep 0.25
  done

  msg=
  case "$fn" in
    *.mission) msg=org.mwptools.mwp.LoadMission ;;
    *.TXT)     msg=org.mwptools.mwp.LoadBlackbox ;;
    *.log)     msg=org.mwptools.mwp.LoadMwpLog ;;
  esac
  [ -n "$msg" ] && dbus-send --session --print-reply=literal \
			    --dest=org.mwptools.mwp \
			    /org/mwptools/mwp $msg string:"$fn"

}

# We do missions first, as it's OK to load a mission then play a log
# However, we will only play a single log, as otherwise it gets too
# complex scheduling multiple logs in mwp.

for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
do
  case "$F" in
    *.mission) to_mwp "$F" ;;
  esac
done

for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
do
  case "$F" in
    *.TXT|*.log ) to_mwp "$F" ; exit 0  ;;
  esac
done

exit 0
