#!/usr/bin/env bash
# a script to start my favorite terminal emulator

version=7
args=( )
foreground=false

usage () {
  echo "Usage: ${0##*/} [-xf] [-e args ...]"
  echo "       ${0##*/} -h"
  echo "       ${0##*/} -v"
}
terminal () {
  if "$foreground"; then
    # Choose a special socket name so that `alacritty msg` will not find this
    # instance and block it.
    local 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; exit;;
    v) echo "term -- Version $version (wrapping alacritty)"; exit;;
    x) set -x;;
    e) args=(-e "$OPTARG" "${@:$OPTIND}"); shift $#;;
    f) foreground=true;;
    *) usage >&2; exit 2;;
  esac
done

terminal "${args[@]}"
