#!/bin/sh

# This script updates PATCHLEVEL in petscversion.h and download/index.html
#
# Usage: createpatch petscrepo
# example usage: createpatch /sandbox/petsc/petsc-dist

if [ $# = 1 ]; then
  petscrepo=$1
else
  echo "Error: petscrepo not specified. Usge: createpatch petscrepo"
  exit
fi

# check petscrepo to be valid
if [ ! -d $petscrepo ]; then
  echo "Error: dir $petscrepo does not exist"
  exit
fi
if [ ! -d $petscrepo/config/BuildSystem ]; then
  echo "Error: dir $petscrepo/config/BuildSystem does not exist"
  exit
fi
cd $petscrepo

if [ ! -f include/petscversion.h ]; then
  echo "Error: dir $petscrepo/include/petscversion.h does not exist"
  exit
fi

if [ ! -f src/docs/website/download/index.html ]; then
  echo "Error: dir $petscrepo/src/docs/website/download/index.html does not exist"
  exit
fi

# check if all files are checked in
a=`hg status -m | wc -l`
b=`hg status -m -R config/BuildSystem | wc -l`
if [ "${a}" != "0" -o "${b}" != "0" ]; then
  echo "*** Mercurial edited files exist. Cannot proceed! ****"
  hg status -m
  hg status -m -R config/BuildSystem
  exit
fi

version_release=`grep '^#define PETSC_VERSION_RELEASE ' include/petscversion.h |tr -s ' ' | cut -d ' ' -f 3`
version_major=`grep '^#define PETSC_VERSION_MAJOR ' include/petscversion.h |tr -s ' ' | cut -d ' ' -f 3`
version_minor=`grep '^#define PETSC_VERSION_MINOR ' include/petscversion.h |tr -s ' ' | cut -d ' ' -f 3`
version_patch=`grep '^#define PETSC_VERSION_PATCH ' include/petscversion.h |tr -s ' ' | cut -d ' ' -f 3`

if  [ ${version_release} = 0 ]; then
  echo "Error: cannot update patchlevel for petsc-dev."
  exit
fi

# crank up patchlevel
new_version_patch=`expr $version_patch + 1`

oldver=${version_major}.${version_minor}-p${version_patch}
newver=${version_major}.${version_minor}-p${new_version_patch}

echo #########################################################
echo ## updating patchlevel from $version_patch to $new_version_patch  ##
echo #########################################################


# Update patchlevel in petscversion.h
/bin/mv include/petscversion.h include/petscversion.h.bak
cat include/petscversion.h.bak | \
  sed -e "s/#define PETSC_VERSION_PATCH .*/#define PETSC_VERSION_PATCH      ${new_version_patch}/" > include/petscversion.h
/bin/rm -f include/petscversion.h.bak

# Update patchlevel in download/index.html

patchlevel=0
/bin/mv src/docs/website/download/index.html src/docs/website/download/index.html.bak
cat src/docs/website/download/index.html.bak | \
  sed -e "s/-${oldver}.tar.gz/-${newver}.tar.gz/g" > src/docs/website/download/index.html
/bin/rm -f src/docs/website/download/index.html.bak

# now create a changeset
hg commit -m"Increase patchlevel to ${newver}" include/petscversion.h src/docs/website/download/index.html
echo #########################################################
echo # Created patch for the following change                #
echo #########################################################
hg export tip
