#!/bin/sh -f

if [ $# -ne 2 ]; then
  echo usage: patch-apply patchfilename destdir
  exit 1
fi

if [ `which bzip2 |cut -b8-9` = no ]; then
  echo bzip2 is required to run this script
  exit 1
fi 
  
if [ `which xdelta |cut -b8-9` = no ]; then
  echo xdelta is required to run this script
  exit 1
fi

if [ `which tar |cut -b8-9` = no ]; then
  echo tar is required to run this script
  exit 1
fi

patchfilename=$1
destdir=$2

rm -f ${destdir}/temp.tar.bz2 ${destdir}/temp.tar
cp ${patchfilename} ${destdir}/temp.tar.bz2

curdir=`pwd`
cd ${destdir}
bzip2 -d temp.tar.bz2
tar xf temp.tar
xdfiles=`ls -1 | grep '\.xd$' | sed '/\.xd/s///'`
for file in ${xdfiles}
do
  perm1=`ls -l ${file} | cut -b2`
  perm2=`ls -l ${file} | cut -b3`
  perm3=`ls -l ${file} | cut -b4`
  perm4=`ls -l ${file} | cut -b5`
  perm5=`ls -l ${file} | cut -b6`
  perm6=`ls -l ${file} | cut -b7`
  perm7=`ls -l ${file} | cut -b8`
  perm8=`ls -l ${file} | cut -b9`
  perm9=`ls -l ${file} | cut -b10`
  xdelta patch ${file} ${file}.xd ${file}.new
  rm -f ${file}.xd

  if [ ${perm1} = r ]; then
    chmod u+r ${file}.new
  else
    chmod u-r ${file}.new
  fi

  if [ ${perm2} = w ]; then
    chmod u+w ${file}.new
  else
    chmod u-w ${file}.new
  fi

  if [ ${perm3} = x ]; then
    chmod u+x ${file}.new
  else
    chmod u-x ${file}.new
  fi

  if [ ${perm4} = r ]; then
    chmod g+r ${file}.new
  else
    chmod g-r ${file}.new
  fi

  if [ ${perm5} = w ]; then
    chmod g+w ${file}.new
  else
    chmod g-w ${file}.new
  fi

  if [ ${perm6} = x ]; then
    chmod g+x ${file}.new
  else
    chmod g-x ${file}.new
  fi

  if [ ${perm7} = r ]; then
    chmod o+r ${file}.new
  else
    chmod o-r ${file}.new
  fi

  if [ ${perm8} = w ]; then
    chmod o+w ${file}.new
  else
    chmod o-w ${file}.new
  fi

  if [ ${perm9} = x ]; then
    chmod o+x ${file}.new
  else
    chmod o-x ${file}.new
  fi

  mv ${file}.new ${file}
done

cd ${curdir}
rm -f ${destdir}/temp.tar.bz2 ${destdir}/temp.tar

exit 0
