#!/bin/sh

# Create a temp dir, spawn a shell there, delete when done
tmp() {
  dir="$(mktemp -d "${TMPDIR:-/tmp}/${LOGNAME-${USER}}.tmp.XXXXXXXX")"
  (
    cd "${dir}" || return
    ${SHELL}
  )
  rm -rf "${dir}"
}

tmpr() {
  tmp=${TMPDIR:-/tmp}
  dir=${tmp}/$$.tmpsh

  mkdir -p "${dir}"
  trap 'command rm -rf -- "${dir:-?}"' EXIT INT TERM HUP

  cd "${dir}" || :
  (${SHELL:-/bin/sh})
}

# create temp directory
tmpw() {
  # shellcheck disable=SC2012,SC2046,SC2312
  [ -n "$1" ] \
    && cd /tmp/workspaces \
    && cd $(ls -t | fzf --preview='ls -A {}') \
    && return 0
  r=/tmp/workspaces/"$(xxd -l3 -ps /dev/urandom)"
  mkdir -p "${r}" && cd "${r}" || return
  git init
}

tmpwork() {
  case "$#" in
    1)
      workingdir="${TMPDIR:-/tmp}"'/workspaces'
      test -d "${workingdir-}" \
        command -p -- mkdir -p "${workingdir}"
      # shellcheck disable=SC2312
      cd "${TMPDIR:-/tmp}"'/workspaces' \
        && cd "$(find . -exec ls -t -- {} + | fzf --preview 'ls -A {}')" \
        && return 0
      ;;
    *)
      tdir="${TMPDIR:-/tmp}/workspaces/$(xxd -l3 -ps /dev/urandom)"
      mkdir -p "${tdir}" && cd "${tdir}" || return
      git init
      ;;
  esac
}

temp() {
  # shellcheck disable=SC2046,SC2249
  case "$(uname)" in
    Linux*)
      cd $(mktemp -d --tmpdir="${HOME}"/tmp "$(date +'%Y%m%d').$1${1:+.}XXXXXX") || :
      ;;
    Darwin | Freebsd*)
      # shellcheck disable=SC2312
      cd $(mktemp -d "${HOME}/tmp/$(date +'%Y%m%d').$1${1:+.}XXXXXX") || :
      ;;
  esac
  git first
}

# t() { cd $(mktemp -d /tmp/$1.XXXX) || :; }

# like to automate the "popd && rm" part in the alias directly. this
# bash function enters a subshell inside the tmpdir and when exit or ^D,
# it pops back to the previous directory and deletes the tmpdir – with a
# little safeguard when you mounted something inside it!
tmps() {
  history -w || true
  t=$(mktemp --tmpdir -d tmpdir-XXXXXX) \
    && {
      ${SHELL} -c \
        "cd '${t}' \
        && printf '\033[31m%s\033[0m\n' 'this directory will be removed upon exit' \
        && pwd \
        && exec ${SHELL}" \
        || true
    } \
    && if awk '{ print $2 }' /etc/mtab | grep "${t}"; then
      printf '%b\n' "\033[31maborting removal due to mounts\033[0m" >&2
    else
      printf '%b\n' "\033[31mremoving temporary directory ...\033[0m" >&2
      rm -rf "${t}"
    fi
}

# use cd because rarely popd at the end, usually just close the
# shell once done with it.
tt() {
  tmpdir=$(mktemp -d)
  [ -d "${tmpdir}" ] || return
  cd "${tmpdir}" || return
  # shellcheck disable=SC2046
  trap 'rm -rf $tmpdir' EXIT
}
