#!/bin/bash

# Set up command recording wrapper

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

if [ ${#BASH_SOURCE[@]} -lt 2 ] && [ $# -eq 0 ]
then
  echo "usage: WRAPDIR=dir LOGPATH=log.txt record-commands COMMAND..."
  echo 'Then examine log.txt. "record-commands echo" to just setup $WRAPDIR'
  exit 1
fi

if [ ! -x "$WRAPDIR/logpath" ]
then
  mkdir -p "$WRAPDIR" || exit 1
  [ -e "$(which logpath)" ] && cp -H "$(which logpath)" "$WRAPDIR/logpath" ||
    PREFIX="$WRAPDIR/" scripts/single.sh logpath || exit 1
  tr : '\n' <<< "$PATH" | while read i; do
    find "$i" -type f,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.
export PATH="$WRAPDIR:$PATH"
if [ ${#BASH_SOURCE[@]} -lt 2 ]
then
  "$@"
  X=$?
  [ -n "$RM" ] && "$RM" -rf "$WRAPDIR"

  exit $X
fi

