#!/bin/bash

if [ "`uname`" != " SunOS" ]
then
   _no_svn="--exclude .svn"
   _no_git="--exclude .git"
fi

_grep_no_svn="| grep -vw [.]svn"
_grep_no_git="| grep -vw [.]git"

unset OpenSsl
if ! which base64 2> /dev/null | grep '^/' > /dev/null 2>&1
then
   OpenSsl="`which openssl 2> /dev/null | grep '^/'`"
fi
  
# Collect all of them
_no_vcs="`set | egrep '^_no_[a-z]{3}=' | grep -v '^_no_vcs=' | \
          sed -e 's/^/$/' -e's/=.*//' | tr '\n' ' '`"
_grep_no_vcs="`set | egrep '^_grep_no_[a-z]{3}=' | grep -v '^_grep_no_vcs=' | \
               sed -e 's/^/$/' -e's/=.*//' | tr '\n' ' '`"

# Slow output for tmux :-(
if [ "$TERM" = "screen" ]
then
   Cat=SlowLines
else
   Cat=cat
fi

SlowLines()
{
   while read -r Line
   do
      echo "$Line"
      sleep .001
   done
}

while echo "$1" | egrep '^--add-[a-z]{3}' > /dev/null 2>&1
do
   # Remove the provided vcs type from the xclude var
   # Using vcs will remove the whole exclude list
   VCS=`echo $1 | sed -r 's/^--add-([a-z]{3}).*/\1/'`
   unset _no_$VCS
   unset _grep_no_$VCS
   shift
done

if [ $# -lt 1 ]
then
   echo
   echo "   Usage: `basename $0` [--add-vcs-content] file [file]"
   echo
   exit 1
fi

# For minimal linux installs without tar, we use cpio in ustar mode
(
   if which tar 2> /dev/null | grep '^/' > /dev/null 2>&1
   then
      tar `eval echo $_no_vcs` -cvf - $* | gzip -c | $OpenSsl base64
   else
      # Show the file list, including errors and remove the /
      eval find $* `eval echo $_grep_no_vcs` 2>&1 | sed 's,^/,,'
      # The base64 block in ustar format 
      eval find $* `eval echo $_grep_no_vcs` 2> /dev/null | \
      cpio -o -H ustar --no-absolute-filenames 2> /dev/null | \
      gzip -c | $OpenSsl base64
   fi
) | $Cat
