#!/bin/bash

# Set up command recording wrapper

[ -z "$WRAPDIR" ] && WRAPDIR="$PWD"/record-commands && RM=$(which rm)
[ -z "$LOGPATH" ] && export LOGPATH="$PWD"/log.txt

if [ ! -x "$WRAPDIR/logpath" ]
then
  LOG="$(which logpath)"
  mkdir -p "$WRAPDIR" || exit 1
  [ -e "$LOG" ] && cp -H "$LOG" "$WRAPDIR/logpath" || { cd "$(dirname $0)/.." &&
    PREFIX="$WRAPDIR/" scripts/single.sh logpath >/dev/null &&
    LOG="$PWD/logpath" || exit 1; }
  tr : '\n' <<< "$PATH" | while read i; do
    find "$i" \( -type f -o -type l \) -maxdepth 1 -executable -exec basename {} \; | \
      while read FILE; do ln -s logpath "$WRAPDIR/$FILE" 2>/dev/null; done
  done
fi

# Delete old log (if any)
rm -f "$LOGPATH"

# When sourced, set up wrapper for current context.
if [ $# -gt 0 ]
then
  PATH="$WRAPDIR:$PATH" "$@"
  X=$?
  [ -n "$RM" ] && "$RM" -rf "$WRAPDIR"

  exit $X
else
  echo export LOGPATH=${LOGPATH@Q} PATH=${WRAPDIR@Q}:${PATH@Q}
fi

