#! /bin/sh

# geditor v0.1
# Wrapper script to run a console text editor in a terminal
# Copyright (c) 2023 Raphaël Halimi <raphael.halimi@gmail.com>

#
# Variables
#

# Configuration files
SYSTEM_CONFIG_FILE="/etc/$(basename "$0").conf"
USER_CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/$(basename "$0").conf"

# Options defaults
EDITOR="editor"

die () {
  MESSAGE="${1:-Error}"
  printf "%s, aborting.\n" "$MESSAGE" >&2
  exit 1
}

print_usage () {
  printf "Usage: %s [OPTION]... [FILE]...\n" "$(basename "$0")"
  printf "Wrapper script to run a console text editor in a terminal\n"
  printf "\nOPTIONS:\n"
  printf "  %-20s%s\n" "-e" "Editor to use (default: $EDITOR)"
  printf "  %-20s%s\n" "-h" "Print this help message"
}


#
# Configuration files
#

[ -e "$SYSTEM_CONFIG_FILE" ] && . "$SYSTEM_CONFIG_FILE"
[ -e "$USER_CONFIG_FILE" ] && . "$USER_CONFIG_FILE"


#
# Options processing
#

while getopts "e:h" OPTION ; do
  case $OPTION in
    e) EDITOR="$OPTARG" ;;
    h) print_usage ; exit 0 ;;
    *) print_usage ; exit 1 ;;
  esac
done ; shift $((OPTIND-1))


#
# Checks
#

# Define editor
if [ -x "$(command -v "$EDITOR")" ] ; then
  COMMAND="$EDITOR"
else
  # Try most common editors
  for TRY_EDITOR in nano vi emacs ; do
    if command -v $TRY_EDITOR > /dev/null ; then
      COMMAND="$TRY_EDITOR"
      break
    fi
  done
  [ -z "$COMMAND" ] && die "Cannot find any editor to execute"
fi


#
# MAIN
#

# Run editor with arguments in twrap
exec twrap "$COMMAND" "$@"
