#!/bin/sh
set -e
EXT=.orig
MYNAME=`basename "$0"`
SRCEDIR=$1
DESTDIR=$2
BASEDIR=`pwd`
mkdir -p "${DESTDIR}" || exit
cd "${SRCEDIR}" || exit
cd "${BASEDIR}"
(cd "${SRCEDIR}";find . -type f -name "*${EXT}")|while read i
do
	DIRNAME=`dirname "${i}"`
	BASENAME=`basename "${i}" ${EXT}`
	if [ -f "${DESTDIR}/${DIRNAME}/${BASENAME}" ]; then
		if (diff "${SRCEDIR}/${DIRNAME}/${BASENAME}${EXT}" \
			"${DESTDIR}/${DIRNAME}/${BASENAME}">/dev/null) then
			:
		else
			echo "Not overwritten: \"${DESTDIR}/${DIRNAME}/${BASENAME}\""
			continue
		fi
	fi
	(cd "${SRCEDIR}";tar cpf - "${DIRNAME}/${BASENAME}${EXT}")|\
	(cd "${DESTDIR}";tar xpf -)
	(cd "${SRCEDIR}";tar cpf - "${DIRNAME}/${BASENAME}")|\
	(cd "${DESTDIR}";tar xpf -)
done
if [ "${MYNAME}" != "setup-bkup.sh" ]; then exit;fi
cd "${DESTDIR}"
find . -type d|sort -r|while read i
do
	cd "${BASEDIR}"
	cd "${SRCEDIR}"
	DIRMODE=`stat -c %a "${i}"`
	DIRUSER=`stat -c %u "${i}"`
	DIRGROP=`stat -c %g "${i}"`
	DIRTIME=`stat -c %y "${i}"|cut -b1-4,6-7,9-10,12-13,15-19|sed 's/:/./'`
	cd "${BASEDIR}"
	cd "${DESTDIR}"
	chmod $DIRMODE "${i}"
	chown $DIRUSER "${i}"
	chgrp $DIRGROP "${i}"
	touch -t $DIRTIME "${i}"
done
