#! /bin/sh

if [ $# -ne 2 ]; then
   echo "Usage:  $0  <svn_repository>  <target_dir> "
   echo ""
   echo "    The required files will be extracted from <svn_repository> "
   echo "    (e.g., 'file:///home/users/tmap/svn/repos/ferret/trunk') "
   echo "    to a temporary directory which this script will create. "
   echo "    The gzipped tar file fer_source.tar.gz will be written in "
   echo "    <target_dir>, which must already exist. "
   echo ""
   exit 1
fi

info=`svn info "$1"`
if [ -z "${info}" ]; then
#  svn has printed an appropriate error message
#  (but still returned a zero status)
   echo ""
   exit 1
fi
repository="$1"

if [ ! -d "$2" ]; then
   echo "$2 does not exist or is not a directory "
   echo ""
   exit 1
fi
# Make sure target_dir is a full pathname
target_dir=`cd "$2" ; pwd`

# Decide what to call the directory checked-out from svn
datestamp=`date +%F`
echo ${repository} | grep -q 'pyferret$'
if [ $? -eq 0 ]; then
   fer_name="pyferret_${datestamp}"
else
   fer_name="ferret_${datestamp}"
fi

# Make a clean temporary directory for the tar file contents
if [ "$TMPDIR" != "" ]; then
   temp_dir="${TMPDIR}/fer_src_$$"
else
   temp_dir="/tmp/fer_src_$$"
fi
rm -fr ${temp_dir}
mkdir ${temp_dir}
cd ${temp_dir}

# Checkout the required files
echo "Extracting Ferret source code "
echo "from ${repository} "
echo "to ${temp_dir}/${fer_name} "
svn checkout -q ${repository} ${fer_name}

# Create the tar file
ctar_file="${target_dir}/fer_source.tar.gz"
echo ""
echo "The tar file will be created from the contents "
echo "(except for the .svn subdirectories) of "
echo "${temp_dir}"
echo "(which can now be examined or tweaked from another shell/window)"
echo ""
echo -n "Create gzipped tar file ${ctar_file} (y/n)? "
read ans
while [ "${ans}" != "y" -a "${ans}" != "n" ]; do
   echo -n "Answer either y or n: "
   read ans
done
if [ "${ans}" = "y" ]; then
   echo ""
   rm -f "${ctar_file}"
   tar czf "${ctar_file}" --exclude .svn "${fer_name}"
   echo ""
   ls -l "${ctar_file}"
else
   echo ""
   echo "Tar file NOT created"
fi

# Clean up
echo ""
echo "Cleaning up - removing ${temp_dir}"
cd "${target_dir}"
rm -fr "${temp_dir}"
echo ""

