#!/bin/sh

# twrap v0.3
# Wrapper script to run a command through a terminal if needed
# Copyright (c) 2022 Raphaël Halimi <raphael.halimi@gmail.com>

# Tested with xterm and gnome-terminal.wrapper, other terminals may or may not
# work


#
# Variables
#

# Options defaults
TERMINAL="x-terminal-emulator"

# Internal variables
SCRIPT_NAME="${0##*/}"
SYSTEM_CONFIG_FILE="/etc/$SCRIPT_NAME.conf"
USER_CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/$SCRIPT_NAME.conf"


#
# Functions
#

# Print functions
print_error () { printf "ERROR: %s\n" "$@" >&2 ; }
print_option () { printf "  -%-4s%s\n" "${1#-}" "$2" ; }

# Die
die () { print_error "${1:-Fatal error}, aborting." ; exit 1 ; }

# Print usage
print_usage () {
  printf "Usage: %s [OPTION]... COMMAND [ARGUMENT]...\n" "$SCRIPT_NAME"
  printf "Wrapper script to run a command through a terminal if needed\n"
  printf "\nOPTIONS:\n"
  print_option "t" "Terminal to use (default: $TERMINAL)"
  print_option "h" "Print this help message"
  printf "\nCOMMAND, ARGUMENT:\n"
  printf "Command to run through the wrapper, and its arguments.\n"
}


#
# Options
#

# Configuration files
for CONFFILE in "$SYSTEM_CONFIG_FILE" "$USER_CONFIG_FILE" ; do
  if [ -e "$CONFFILE" ] ; then . "$CONFFILE" ; fi
done

# Command line
while getopts "t:h" OPTION ; do
  case $OPTION in
    t) TERMINAL="$OPTARG" ;;
    h) print_usage ; exit 0 ;;
    *) print_usage ; exit 1 ;;
  esac
done ; shift $((OPTIND-1))


#
# Checks
#

# Exit if we don't have at least one argument
[ $# -ge 1 ] || die "No command to run"


#
# Main
#

# Extract program from arguments
COMMAND="$1"
shift

# Check if we are in a terminal
if [ -t 0 ] ; then

  printf "\033]0;$COMMAND $*\007"
  exec "$COMMAND" "$@"

else

  # Check if we can find configured terminal program in PATH
  command -v "$TERMINAL" >/dev/null || die "Cannot find configured terminal program '$TERMINAL' in PATH"

  # Check if a display is available
  [ -n "$DISPLAY" ] || die "No terminal nor display to use"

  # Run program in a terminal
  exec "$TERMINAL" -T "$COMMAND${*:+ $*}" -e "$COMMAND" "$@"

fi
