#!/bin/ksh
 
#
# This is inspired by the "pkgconf" script by Christopher Rabson.
# http://www.robots.ox.ac.uk/~kit/pkgconv.html
# However, that script made improper use of 'pkgadd -R', which is NOT
# the appropriate way to relocate a package
#
# This script checks whether a package has been made with a relocatable
# BASEDIR. If and only if it has, it will let you change the basedir.
#
# An alternative is simply to use "pkgadd -a", but that will ask you a lot
# more questions.
#
# Phil Brown, phil@bolthole.com, http://www.bolthole.com/solaris/
#
 
 
PATH=/usr/bin:/usr/sbin:/sbin


usage(){
	print "You need to specify a pkg file to convert, and a new basename"
	print "You can find out the old basename, with"
	print "   pkginfo -r -d pkgfile"
	print "This script will then generate a new pkg file for you to use"
	print "with pkgadd"
	exit 1
}

PKGFILE="$1"
NEWBASE="$2"
if [[ "$PKGFILE" == "" ]] ; then
	usage
fi
if [[ ! -f "$PKGFILE" ]] ; then
	usage
fi

head -1 $PKGFILE | grep 'PaCkAgE DaTaStReAm' >/dev/null
if [[ $? -ne 0 ]] ; then
	print $PKGFILE is not a SysV PKG file.
	exit 1
fi

if [[ "$NEWBASE" == "" ]] ; then
	usage
fi

OLDBASE=`pkginfo -r -d $PKGFILE`
if [[ "$OLDBASE" == "" ]] ; then
	print ERROR: no BASEDIR set in package. Cannot relocate it
	exit 1
fi
if [[ "$OLDBASE" == "/" ]] ; then
	print "ERROR: BASEDIR set to '/' in package. Cannot relocate it"
	exit 1
fi

print "attempting to change BASEDIR from $OLDBASE to $NEWBASE"

PKG=`awk 'NR==2 {print $1; exit;}' $PKGFILE`

pkgtrans $PKGFILE . $PKG </dev/null

cd $PKG

egrep -v '^BASEDIR=' pkginfo >pkginfo.tmp
print "BASEDIR=$NEWBASE" >>pkginfo.tmp
mv pkginfo.tmp pkginfo


# Now do the 'pkgmap' file.
#
size=`wc -c pkginfo | cut -f6 -d' '`
chksum=`sum pkginfo | cut -f1 -d' '`
mtime=`grep 'pkginfo' pkgmap | cut -f6 -d' '`

egrep -v ' pkginfo ' pkgmap >pkgmap.tmp
 
print "1 i pkginfo $size $chksum $mtime">>pkgmap.tmp
mv pkgmap.tmp pkgmap

cd ..
pkgtrans . $PKGFILE.new $PKG </dev/null

rm -rf $PKG

print "You may now run 'pkgadd -d $PKGFILE.new'"
