#!/bin/sh
#
# Copyright (c) 2008 by Bruce Blinn
#
# NAME
#	dircopy - copy a directory
#
# SYNOPSIS
#	dircopy [-v] directory1 directory2
#
# DESCRIPTION
#	This command will copy the contents of one directory to
#	another.  The destination directory and any subdirectories
#	will be created as needed.
#
# OPTIONS
#	-v	Verbose.  Print the names of the files as they are
#		being copied.
#
# RETURN VALUE
#	0	Successful completion.
#	1	Error - see the message written to standard error.
#
####################################################################
CMDNAME=$(basename $0)
USAGE="Usage: $CMDNAME [-v] directory1 directory2"
CURDIR=$(pwd)		# Current directory.
V=			# Verbose option to tar.
DIR1=			# Source directory.
DIR2=			# Destination directory.
ERRMSG=/tmp/errmsg.$$	# Error messages from cpio.

trap 'rm -f /tmp/*.$$' EXIT

while getopts v OPT
do
	case $OPT in
		v)	V="v"
			;;
		\?)	echo "$USAGE" 1>&2
			exit 1
			;;
	esac
done
shift $((OPTIND - 1))

if [ $# -ne 2 ]; then
	echo "$USAGE" 1>&2
	exit 1
fi

DIR1=$1
DIR2=$2

if [ ! -d "$DIR1" ]; then
	echo "$DIR1 is not a directory." 1>&2
	exit 1
fi

if [ ! -d "$DIR2" ]; then
	mkdir -p "$DIR2"
	if [ $? -ne 0 ]; then
		echo "$CMDNAME: Cannot create $DIR2" 1>&2
		exit 1
	fi
fi

cd "$DIR2"
DIR2=$(pwd)
cd $CURDIR

cd $DIR1
find . -depth -print | cpio -pdmu$V $DIR2 2>$ERRMSG
if [ $? -ne 0 ]; then
	cat $ERRMSG 1>&2
	exit 1
fi
