#!/bin/bash

# TODO
# * colorize the filenames when output to tty.

usage() {
  echo 1>&2 "
Usage: bunch file ...

Catenates a text files so they can be edited all at once.
Use unbunch to re-extract them.
Files with no trailing newline come through intact, unless sed is BSD.

Author: dave@yost.com  -  Last rev: 2015-01-30
"
  exit 2
}

case $1 in
"" | --help) usage
esac

separator='========'

echo '#!/usr/bin/env unbunch'
echo '# See http://yost.com/computers/bunch/'

for x do
  trailingSlash=
  if [[ $x == - ]] ; then
    # compatibility with old versions
    x=/dev/stdin
  elif [[ -f $x && -r $x ]] ; then
    :
  elif [[ -d $x ]] ; then
    if [[ -n $(ls -A $x 2> /dev/null) ]] ; then
      # Dir is not empty.
      continue
    fi
    trailingSlash=/
  else
    echo 1>&2 "bunch: no such file: $x"
    continue
  fi
  
  echo $separator ${x##./}$trailingSlash
  if [[ -z $trailingSlash ]] ; then
    # Escape a separator line with an initial backslash.
    sed 's,^\\*\('$separator' |'$separator'$\),\\\1,' < $x
    # If the last line had no newline, this will terminate it; 
    # otherwise, it will cause a blank line. Unbunch will understand.
    echo
  fi
done

echo $separator
