# author: deadc0de6 (https://github.com/deadc0de6)
# Copyright (c) 2017, deadc0de6
#
# file to be sourced from test scripts
#
# for i in *.sh; do ./$i >/dev/null 2>&1; find /tmp/ -maxdepth 1 -type f -iname 'tmp*' >> /tmp/$i.log; find /tmp/ -maxdepth 1 -type d -iname 'tmp.*-dotdrop-tests' >> /tmp/$i.log; find /tmp/ -maxdepth 1 -type d  -iname 'dotdrop-*' >> /tmp/$i.log; wc -l /tmp/$i.log; [ "`wc -l /tmp/$i.log | awk '{print $1}'`" -gt "0" ] && break; done

declare -a to_be_cleared

# add a file/directory to be cleared
# on exit
#
# $1: file path to clear
clear_on_exit()
{
  local len="${#to_be_cleared[*]}"
  to_be_cleared[${len}]="$1"
  if [ "${len}" = "0" ]; then
    # set trap
    trap on_exit EXIT
  fi
}

# clear files
on_exit()
{
  for i in "${to_be_cleared[@]}"; do
    rm -rf "${i}"
  done
}

# create a directory with sub-dirs and file
# for tests
#
# $1: path of the parent directory to create
# ret: set the variable token that allows to check
create_dir()
{
  dirs="a/aa a/ab a/ac b/ba c"
  mkdir -p ${1}
  for d in ${dirs}; do
    # create some dirs
    mkdir -p ${1}/${d}
    # create some files
    fn=`echo ${d} | sed 's#/#-#g'`
    f="${1}/${d}/${fn}"
    echo "${d}" > ${f}
    token=${f}
  done
}

# create a clean config file
#
# $1: path to save to
create_conf()
{
  cat > ${1} << _EOF
config:
  backup: true
  create: true
  dotpath: dotfiles
dotfiles:
profiles:
_EOF
}

# osx tricks
# brew install coreutils gnu-sed
if [[ $OSTYPE == 'darwin'* ]]; then
  mktemp() {
    gmktemp "$@"
  }
  stat() {
    gstat "$@"
  }
  sed() {
    gsed "$@"
  }
  wc() {
    gwc "$@"
  }
  date() {
    gdate "$@"
  }
  chmod() {
    gchmod "$@"
  }
  readlink() {
    greadlink "$@"
  }
  realpath() {
    grealpath "$@"
  }

  export -f mktemp
  export -f stat
  export -f sed
  export -f wc
  export -f date
  export -f chmod
  export -f readlink
  export -f realpath
fi

# workdir tricks
# when tests are called without using the
# top level tests.sh script which sets the workdir
if [ -z "${DOTDROP_WORKDIR}" ]; then
  _workdir="/tmp/dotdrop-test-workdir"
  export DOTDROP_WORKDIR="${_workdir}"
  clear_on_exit "${_workdir}"
fi