#!/bin/sh
# kupfer      A convenient command and access tool
#
# Copyright 2007--2017 Ulrik Sverdrup
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# This script invokes kupfer by calling an already running instance, or
# starting a new if none is found running.

_hasprefix () {
	test "x${1#$2}" != "x$1"
}

PYTHON="/usr/bin/python3"
PYTHONDIR="/usr/share/kupfer"
_hasprefix "$PYTHON" "@"  && PYTHON=python3
_hasprefix "$PYTHONDIR" "@" && PYTHONDIR=$(dirname $(readlink -f -- $0))/..

SERVICE="io.github.kupferlauncher"
OBJ="/io/github/kupferlauncher"
IFACE="io.github.kupferlauncher.Listener"

# If there are any options, like "--help", we run Kupfer directly
_hasprefix "$1" "--"
KUPFER_HAS_OPTIONS=$?

# We allow reading directly from stdin if we pipe text into Kupfer
if [ ! -t 0 -a $# = 0 -a -z "$DESKTOP_STARTUP_ID" ]
then
	echo "kupfer: Reading from stdin" >&2
	TEXT_INPUT=$(cat)
fi


test $KUPFER_HAS_OPTIONS != 0 && dbus-send --type=method_call --print-reply \
	--dest=$SERVICE $OBJ $IFACE.PresentOnDisplay string:"$DISPLAY" \
	"string:$DESKTOP_STARTUP_ID" >/dev/null 2>&1
KUPFER_RUNNING=$?

if test \( -n "$TEXT_INPUT" -a $KUPFER_HAS_OPTIONS != 0 \)
then
	dbus-send --type=method_call --dest=$SERVICE $OBJ \
		$IFACE.PutTextOnDisplay string:"$TEXT_INPUT" \
		string:"$DISPLAY" string:"$DESKTOP_STARTUP_ID"
fi

_realpaths () {
	# Emit realpaths for arguments, separated by NUL bytes
	while test $# != 0
	do
		LINK=$(readlink -e -- "$1")
		if test $? != 0 ; then
			echo "Error: $1 does not exist" >&2
			shift
			continue
		fi
		printf "%s\0" "$LINK"
		shift
	done
}

if test \( -n "$1" -a $KUPFER_HAS_OPTIONS != 0 \)
then
	# NOTE: We must escape commas here since it is dbus-send's
	# array item separator. This is then unescaped by kupfer
	ARRAY=$(_realpaths "$@" | sed -e 's/,/%%kupfercomma%%/g' | tr \\0 ,)
	dbus-send --type=method_call --dest=$SERVICE $OBJ \
		$IFACE.PutFilesOnDisplay array:string:"$ARRAY" \
		string:"$DISPLAY" string:"$DESKTOP_STARTUP_ID"
fi



if test $KUPFER_RUNNING != 0
then
	exec ${PYTHON} "$PYTHONDIR/kupfer.py" "$@"
fi
