#! /bin/bash

if [ "$3" == "" -o ! -f $1 -o ! -f $2 ]; then
    cat <<EOF
  ** usage: mergeJars.sh <first> <second> <FinalResult.jar>
     Merge two Jars into a final JAR.  The two Jars must exist, and the
       manifest of the *first* Jar will be kept.
EOF
    exit 1;
fi

first=$1;
second=$2;
result=$3;
tempdir=.merge.tmp

mkdir $tempdir
cp $first $result

secondone="$second"
echo $secondone | egrep '^/'
if [ $? == "1" ]; then
    secondone="../$second"
fi

resultone="$result"
echo $resultone | egrep '^/'
if [ $? == "1" ]; then
    resultone="../$result"
fi

pushd $tempdir &>/dev/null

jar -xf $secondone
rm -rf META-INF
jar tf $secondone | grep -v 'META-INF' | egrep -v '/$' | xargs jar -uf $resultone

popd &>/dev/null

rm -rf $tempdir

