#!/bin/bash

## Copyright (C) 2012 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

set -x
set -e

if [ -e "/etc/alternatives/x-terminal-emulator" ]; then
   ## Lets see where for example /etc/alternatives/aptitude links to.
   if readlink_result="$(readlink "/etc/alternatives/x-terminal-emulator")" ; then
      ## Symlink could be read. Lets use it.
      etc_alternatives_x_terminal_emulator_full_path="$readlink_result"
      etc_alternatives_x_terminal_emulator_base_name="${etc_alternatives_x_terminal_emulator_full_path##*/}"
   fi
fi

supported_terminal_emulator_apps="
   xfce4-terminal
   xterm
   konsole
"

for terminal_emulator_app_supported in $supported_terminal_emulator_apps ; do
   if [ "$etc_alternatives_x_terminal_emulator_base_name" = "$terminal_emulator_app_supported" ]; then
      [ -n "$terminal_emulator_app" ] || terminal_emulator_app="$terminal_emulator_app_supported"
   fi
done

if command -v xfce4-terminal >/dev/null 2>&1; then
   [ -n "$terminal_emulator_app" ] || terminal_emulator_app="xfce4-terminal"
elif command -v xterm >/dev/null 2>&1; then
   [ -n "$terminal_emulator_app" ] || terminal_emulator_app="xterm"
elif command -v konsole >/dev/null 2>&1; then
   [ -n "$terminal_emulator_app" ] || terminal_emulator_app="konsole"
elif [ ! "$etc_alternatives_x_terminal_emulator_base_name" = "" ]; then
   [ -n "$terminal_emulator_app" ] || terminal_emulator_app="$etc_alternatives_x_terminal_emulator_base_name"
   [ -n "$terminal_emulator_extra_args" ] || terminal_emulator_extra_args="-e"
else
   error_message="$0: No supported terminal_emulator_app installed! Please install either:
$supported_terminal_emulator_apps

PPID: $PPID
$0 was called by: $(ps --no-headers -o command $PPID)" || true
   kdialog --sorry "$error_message" >/dev/null 2>&1 || true
   zenity --error --text "$error_message" >/dev/null 2>&1 || true
   echo "$error_message" >&2
fi

if [ "$terminal_emulator_app" = "xfce4-terminal" ]; then
   [ -n "$terminal_emulator_extra_args" ] || terminal_emulator_extra_args="--execute"
fi

if [ "$terminal_emulator_app" = "xterm" ]; then
   [ -n "$terminal_emulator_extra_args" ] || terminal_emulator_extra_args="-e"
fi

if command -v qubesdb-read >/dev/null 2>&1; then
   ## Qubes.
   if [ "$terminal_emulator_app" = "konsole" ]; then
      [ -n "$terminal_emulator_extra_args" ] || terminal_emulator_extra_args="--hold -e"
   fi
else
   ## Non-Qubes.
   if [ "$terminal_emulator_app" = "konsole" ]; then
      ## Do not use '--fullscreen' since this starts the window without window
      ## controls (no window close button) which is confusing.
      ## '-e' needs to be the last paramater.
      [ -n "$terminal_emulator_extra_args" ] || terminal_emulator_extra_args="--hold -e"
   fi
fi

$terminal_emulator_app $terminal_emulator_extra_args $@
