#!/bin/bash

if [ -d "$1" ] ; then
   dir=$1
else
   echo "usage: $0 dir"
   exit 1
fi

topdir=/tmp/$USER/centosification

if [ -d $topdir ] ; then
  rm -rf $topdir
fi

if [ ! -d $topdir ] ; then
  mkdir -p $topdir
fi

mkdir -p $topdir/BUILD
mkdir -p $topdir/RPMS
mkdir -p $topdir/SOURCES
mkdir -p $topdir/SPECS
mkdir -p $topdir/SRPMS

#srpm_path=/opt/redhat/linux/enterprise/2.1AS/en/os/i386/SRPMS/
#srpm=`cat $dir/SRPM`
srpm=`ls $dir/*.src.rpm`

rpm --define _topdir$topdir -i $srpm_path$srpm

prepend()
{
   # $1 = filename
   # $2 = line of text
   echo "$2" > $1.new
   cat $1 >> $1.new
   cp -f $1.new $1
   rm $1.new
}

replace()
{
   # $1 = filename
   # $2 = existing text
   # $3 = new text
   /usr/bin/perl -pi -e "s|${2}|${3}|" $1
}

# centosrelease the spec file...
spec=$topdir/SPECS/*.spec
if grep "^%define centos_release" $spec ; then
   echo "Need to increment centos_release"
else
   release=1
   if [ -f $dir/RELEASE ] ; then
      release=`cat $dir/RELEASE`
   fi
   #echo "Need to prepend centos_release $release"
   prepend $spec "%define centos_release .$release"
fi

if grep "^%define centos_version" $spec ; then
   echo "centos_version present"
else
   #echo "Need to prepend centos_version"
   prepend $spec "%define centos_version .c2"
fi

if grep "^Release: .*%{centos_version}%{centos_release}" $spec ; then
   echo "Release macros present"
else
   #echo "Need to add Release macros"
   release=`grep '^Release:' $spec | uniq`
   replace $spec "$release" "$release%{centos_version}%{centos_release}"
fi

# apply spec file diff
if [ -f $dir/spec.patch ] ; then
   patch=`pwd`/$dir/spec.patch
   (cd $topdir/SPECS/ ; patch < $patch )
fi

# apply source modifications
for f in `cat $dir/COPY 2> /dev/null` ; do
   cp $dir/$f $topdir/SOURCES/
done

# build into srpm
rpm --define _topdir$topdir -bs $spec
