#! /bin/ksh

[ $# -eq 2 ] || {
  echo "Usage: piprep /path/to/pi /path/to/source"
  exit 1
}

[ -d $1/dist ] || {
  echo "ERROR: $1 does not contain the dist/ directory"
  exit 1
}

[ -d $1/dist/osr5 -o -d $1/dist/uw7 ] || {
  echo "ERROR: $1/dist is incorrectly populated"
  exit 1
}

[ -f $1/dist/macros.gwxlibs ] || {
  echo "ERROR: macros.gwxlibs not in $1/dist"
  exit 1
}

[ -d $2/commonpi ] || {
  echo "ERROR: $2 does not refer to top of opensrc/ source tree"
  exit 1
}

case "$1" in
  /*) ;;
  *) echo "ERROR: $1 must be an absolute path"; exit 1 ;;
esac

case "$2" in
  /*) ;;
  *) echo "ERROR: $2 must be an absolute path"; exit 1 ;;
esac

#
# Create the data directory from scratch
rm -fr $1/data
mkdir $1/data
mkdir $1/data/common
cp $1/dist/macros.gwxlibs $1/data

# Copy the common files into place
cd $2/commonpi/data
find . | sed -e '/\/CVS\//d' -e '/\/CVS$/d' | cpio -pdum $1/data/common 2> /dev/null

# Copy each package's stuff into place
cd $2
for dir in *; do
  case $dir in
    CVS | commonpi) ;;
    *) [ -d $dir/PACKAGING ] && {
         cd $dir/PACKAGING
	 find *$dir | sed -e '/\/CVS\//d' -e '/\/CVS$/d' | cpio -pdum $1/data 2> /dev/null
	 cd ../..
       }
       ;;
  esac
done

#
# Now compile MetaPKG and the new AST pax, both of which the mkopensrc
# script requires to run. We get a modern KSH93 for free when compiling
# AST so use that for the main script too.
#
[ -f $1/metapkg -a -f $1/pax -a -f $1/ksh ] || {
  rm -fr $1/preptmp
  mkdir $1/preptmp
  cd $2/commonpi/src
  find ast metapkg | cpio -pdum $1/preptmp 2> /dev/null
}

[ -f $1/metapkg ] || {
  cd $1/preptmp/metapkg
  make > $1/metapkg.log 2>&1
  [ -f metapkg ] || {
    echo "MetaPKG compile failed ... cannot proceed"
    cd $1
    exit 1
  }
  cp metapkg $1
}

[ -f $1/ksh -a -f $1/pax ] || {
  cd $1/preptmp/ast
  bin/package make > $1/ast.log 2>&1
  asthost=`bin/package host`
  [ -f arch/$asthost/bin/pax -a -f arch/$asthost/bin/ksh ] || {
    echo "AST compile failed ... cannot proceed"
    cd $1
    exit 1
  }
  cp arch/$asthost/bin/pax $1
  cp arch/$asthost/bin/ksh $1
}

cd $1
rm -fr preptmp metapkg.log ast.log

rm -f $1/mkopensrc
echo "#! $1/ksh" > $1/mkopensrc
cat $2/commonpi/bin/mkopensrc >> $1/mkopensrc
chmod 755 $1/metapkg $1/mkopensrc $1/pax $1/ksh
exit 0
