#!/bin/tcsh

set args=""
set clean=0
set rebuild=0
set update=0
set optimize=0
while ($#argv)
 switch ($1)
  case -clean:
   set clean=1;
   breaksw;
  case -rebuild:
   set rebuild=1;
   set clean=1;
   breaksw;
  case -update:
   set update=1;
   breaksw;
  case -opt:
   set optimize=1;
   breaksw;
  default:
   set args=($args $1);
   breaksw;
 endsw
 shift
end

if ($#args != 2) goto usage
if ("$args" == "") goto usage

set version = $args[1]
set group   = $args[2]
set tagsets = tagsets/$group

if (! -e $tagsets) then
  echo "target $group not found in tagsets"
  exit 2
endif

source psconfig.sh $version

set psopts = ""
if ($optimize) set psopts = "$psopts --enable-optimize"

foreach target (`cat $tagsets | grep -v \#`)
 set name = `echo $target | tr ':' ' '`
 set dir = $name[1]
 set tag = $name[2]

 set cwd = `pwd`
 cd ../$dir
 
 echo ""
 echo "***** building $name ($target) *****"
 pwd

 if ($update) then
  switch ($tag)
   case HEAD:
    cvs -q up -d -A
    if ($status) goto failure;
    breaksw;
   case NONE:
    breaksw;
   default:
    cvs -q up -d -r $tag
    if ($status) goto failure;
    breaksw;
  endsw
 endif

 # how do we build this component?
 # - autogen.sh : configure : make : make install
 # - configure : make : make install
 # - make : make install
 # - perl Build.PL : ./Build : ./Build install
 
 if (-e Build.PL) then
    echo $PERL5LIB
    alias psperlbuild
    psperlbuild
    # perl Build.PL --install_path script=$bindir --install_path lib=$libdir --install_path bindoc={$PSCONFDIR}/man/man1 --install_path libdoc={$PSCONFDIR}/man/man3
    if ($status) goto failure;

    ./Build
    if ($status) goto failure;

    ./Build install
    if ($status) goto failure;

    goto success;
 endif

 if ($rebuild && $clean) then
   if (-e configure) rm -f Makefile
   if (-e configure.ac && -e autogen.sh) rm -f configure
 endif

 if (! -e Makefile) set rebuild = 1

 if ($rebuild && ! -e configure && -e autogen.sh) then
    echo psautogen $psopts
    psautogen $psopts
    if ($status) goto failure;
 endif

 if ($rebuild && -e configure) then
    echo psconfigure $psopts
    psconfigure $psopts
    if ($status) goto failure;
 endif

 if (! -e Makefile) goto failure;

 if ($clean) then 
    echo make clean
    make clean
    if ($status) goto failure;
 endif

 make
 if ($status) goto failure;

 make install
 if ($status) goto failure;

 success:
 cd $cwd
end

exit 0

usage:
  echo "USAGE: build (version) (group) [-clean] [-update]"
  exit 2

failure:
  echo "build failed"
  echo "target: $target"
  echo "dir: $dir"
  echo "tag: $tag"
  exit 2
