#!/usr/bin/env bash
# bin/tmp — create a tmp dir under ~/tmp/<yyyy-mm-dd-HHMM[-slug]>.
# Prints the path so you can `cd "$(tmp)"` or invoke with --cd inside zsh.
set -euo pipefail
TMP_ROOT="${TMP_ROOT:-$HOME/tmp}"
mkdir -p "$TMP_ROOT"
stamp=$(date +%Y-%m-%d-%H%M)
slug=""
if [[ $# -gt 0 ]]; then
slug="${*// /-}"
slug="${slug//[^A-Za-z0-9._-]/}"
slug="-$slug"
fi
dir="$TMP_ROOT/${stamp}${slug}"
if [[ -d "$dir" ]]; then
# Collision in the same minute: append a counter.
n=1; while [[ -d "${dir}-${n}" ]]; do ((n++)); done
dir="${dir}-${n}"
fi
mkdir -p "$dir"
printf '%s\n' "$dir"