#!/bin/sh
set -eu

LASTSESSIONIDFILE="${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}}/tmux-last-session-id"

real_tmux() {
  local exec; exec=exec
  if [ -n "${_tmux_eval_only:-}" ]; then
    exec=
  fi
  $exec $(which -a tmux | grep -v $HOME | head -1) "$@"
}

single_tmux_session() {
  local id; id="$1"; shift
  real_tmux new -t "$id" "$@"
}

tmux_session_exists() {
  _tmux_eval_only=1 real_tmux has-session -t "$1"
}

if [ "${1:-}" = last ]; then
  shift
  if [ -f "$LASTSESSIONIDFILE" ]; then
    UUID="$(cat $LASTSESSIONIDFILE)"
    if tmux_session_exists $UUID; then
      echo >&2 Attaching to existing session with ID $UUID…
      single_tmux_session "$(cat $LASTSESSIONIDFILE)" "$@"
    else
      echo >&2 W: No tmux session with ID $UUID found, generating a new one…
    fi
  else
    echo >&2 W: No tmux session ID stored, generating a new one…
  fi

else
  case "${1:-;}" in
    (\;) :;;
    (*) real_tmux "$@";;
  esac
fi

# only without argument create a new session with a random name/id to which we
# can then attach

which() { command -v "$@" >/dev/null;}

if   which uuid; then alias uuidgen=uuid
elif which uuidgen; then :
elif which python3; then
  uuidgen() { python3 -c 'import uuid; print(uuid.uuid1())'; }
elif which python; then
  uuidgen() { python -c 'import uuid; print(uuid.uuid1())'; }
else
  uuidgen() { dd if=/dev/urandom bs=16 count=1 status=none | base64; }
fi
UUID=$(uuidgen)
echo "$UUID" > $LASTSESSIONIDFILE

echo >&2 Starting a new session with ID $UUID…

single_tmux_session $UUID "$@"