#! /bin/sh -e
#
# Compare experiment setups trying to identify file pairs.
#
# $Id$
#

PROGRAM=`basename $0`

die () {
    echo "$@" >&2
    exit 1
}

cp_exp_file () {
    exp_a=$1
    exp_b=$2
    file_a=$3
    file_b=$4
    [ -e "$file_b" ] && die "Oops: cannot overwrite existing file '$file_b'"
    case $(file -bi "$file_a") in
    text/*) 
        trap 'rm -f $temp_b' 0
        temp_b=`mktemp`
        sed "s,\<$exp_a\>,$exp_b,g;s,\<${exp_a}_,${exp_b}_,g" "$file_a" > $temp_b
        mv $temp_b "$file_b"
        chmod --reference="$file_a" "$file_b"
        echo "$file_a x> $file_b"
        ;;
    *)
        ln -v "$file_a" "$file_b"
        ;;
    esac
}

[ "x$3" = x ] && die "Oops: invalid number of parameters
Usage: $PROGRAM experiment_id_a experiment_id_b path_to_a [path_to_b]"

unset CDPATH

EXP_A=$1
EXP_B=$2
PATH_A=$3
# If path to b is not set or empty, use path to a as template
PATH_B=${4:-`echo "$PATH_A" | sed "s,$EXP_A,$EXP_B,g"`}

if [ -d "$PATH_A" ]
then :
else
    FIND_A="-name $(basename $PATH_A)"
    PATH_A=$(dirname $PATH_A)
    FIND_B=$(basename $PATH_B)
    PATH_B=$(dirname $PATH_B)
fi

mkdir -vp "$PATH_B"

for DIR_A in $(
    {
        ( cd "$PATH_A" &&
          find . -type d ! -name . $FIND_A )
    } | sed 's,^\./,,'
)
do
    DIR_B=`echo "$DIR_A" | sed "s,$EXP_A,$EXP_B,g"`
    mkdir -v "$PATH_B"/"$DIR_B"
done
    
for FILE_A in $(
    {
        ( cd "$PATH_A" &&
          find . ! -type d $FIND_A )
    } | sed 's,^\./,,'
)
do
    FILE_B=${FIND_B:-$(echo "$FILE_A" | sed "s,$EXP_A,$EXP_B,g")}
    cp_exp_file "$EXP_A" "$EXP_B" "$PATH_A/$FILE_A" "$PATH_B/$FILE_B" ||
        STATUS=$?
done

exit $STATUS