#!/usr/bin/env bash
#
# term - a script to start your favorite terminal emulator

# shellcheck shell=bash
version=11
args=( )
foreground=false

usage() {
    printf %s "\
  $(basename "$0") [-xf] [-e args ...] [-h|-v]
"
    exit 0
}

terminal() {
  if "${foreground}"; then
    # Choose a special socket name so that `alacritty msg` will not find this
    # instance and block it.
    # shellcheck disable=SC2154
    socket=${XDG_RUNTIME_DIR}/standalone-Alacritty-${DISPLAY}-$$.sock
    exec alacritty --socket "${socket}" "$@"
  else
    # Try to connect to an existing Alacritty instance with `alacritty msg`,
    # start a new instance otherwise.
    alacritty msg create-window "$@" \
      || exec alacritty "$@"
  fi
}

while getopts e:fhvx opt; do
  case ${opt} in
    h) usage ;;
    v) echo "term -- Version ${version} (wrapping alacritty)"; exit ;;
    x) set -x ;;
    e) args=(-e "${OPTARG}" "${@:${OPTIND}}"); shift $# ;;
    f) foreground=true ;;
    *) usage >&2 ;;
  esac
done

terminal "${args[@]}"
