#!/usr/bin/env sh

logfile=$(mktemp "${TMPDIR:-/tmp}"/"$(basename "$0")"-"${LOGNAME:-${USER}}".log)

# remove temporary files on exit.
cleanup() {
  ret="$?"
  command -p -- rm -f -- "${logfile}"
  trap - EXIT
  exit "${ret:?}"
}

# logfile="${TMPDIR}/terminal-${USER}.log"
temubin=kitty
dir=

if [ "$1" = "-d" ]; then
  dir="$2"
  echo "${dir}" >>"${logfile}"
  shift 2
fi

if [ -z "${dir}" ]; then
  # exec nohup "${temubin}" "$@" >/dev/null 2>&1 & >>"${logfile}" 2>&1
  exec "${temubin}" "$@" >>"${logfile}" 2>&1
else
  exec "${temubin}" --working-directory "${dir}" "$@" >>"${logfile}" 2>&1
fi

{
  trap cleanup EXIT || :
  trap cleanup TERM || :
  trap cleanup INT || :
  trap cleanup HUP || :
} 2>/dev/null
