#!/bin/bash

# This script generates a special "patch tree" composed of
# new versions of files, original versions and patches between
# two file trees

ORIGFILESDIR="/var/www/abclinuxu/original/portal/" # original source tree
NEWFILESDIR="/var/www/abclinuxu/portal/" # modified source tree
TARGETDIR="patchtree" # output directory

ORIGEXT="orig" # original files will have a $ORIGEXT suffix
PATCHEXT="patch" # patch files will have a $PATCHEXT suffix

function doCopy {
cesta=$(dirname "$1")

# Create the directory tree
mkdir -p "$TARGETDIR/$cesta"

# Copy the new file
cp "$NEWFILESDIR/$1" "$TARGETDIR/$cesta"

# If original file exists...
if [ -f "$ORIGFILESDIR/$1" ]; then
	# copy it
	cp "$ORIGFILESDIR/$1" "$TARGETDIR/${1}.$ORIGEXT"
	# and create a diff
	diff -u "$TARGETDIR/${1}.$ORIGEXT" "$TARGETDIR/$1" > "$TARGETDIR/${1}.$PATCHEXT"
fi
}

# find modified files
diff=$(LC_ALL=C diff -qrN "$ORIGFILESDIR" "$NEWFILESDIR" | awk '{print $2}')

for name in $diff; do
	# get a relative path
	relative="${name#$ORIGFILESDIR}"
	
	doCopy "$relative"
done
