#!/usr/local/bin/perl

$tool = $ENV{"DTOOL"} ;
if ( $tool eq "" ) {
   die "Environment not configured to run CTtools" ;
}

if ($#ARGV == -1) {
   exit print "Usage: ctaddtgt [{bin,a,so,ss,foreign}] target-name ...\n" ;
}

require "$tool/include/ctproj.pl" ;
require "$tool/include/ctvspec.pl" ;
require "$tool/include/ctquery.pl" ;

@arglist = @ARGV ;

$projname = &CTProj ;
$projname =~ tr/A-Z/a-z/ ;
$projroot = &CTProjRoot( $projname ) ;
$pkgname = &CTProjPkg( $projname ) ;
$flav = &CTQueryProj( $projname ) ;
$spec = &CTResolveSpec( $projname, $flav ) ;

# check for package makefile and package install makefile

while ( @arglist != () ) {
   # initialize target type to default
   $type = "bin" ;

   # potentially get the target type
   if ( $arglist[0] eq "bin" ) {
      shift( @arglist ) ;    # already set
   } elsif (( $arglist[0] eq "foreign" ) || ( $arglist[0] eq "a" ) ||
	    ( $arglist[0] eq "so" ) || ( $arglist[0] eq "ss" )) {
      $type = $arglist[0] ;
      shift( @arglist ) ;
   }

   # get the target name
   $tgtname = $arglist[0] ;
   $fulltgtname = $tgtname ;
   shift( @arglist ) ;

   require "$tool/include/ctinstmake.pl" ;
   require "$tool/include/ctcm.pl" ;

   $item = "$projroot/src/$pkgname" ;
   if ( ! &CTCMCheckout( $item, $projname, $spec )) {
       die "Could not checkout package '" . $pkgname . "'\n" ;
   }
   $item = "$projroot/src/$pkgname/Makefile" ;
   if ( ! &CTCMCheckout( $item, $projname, $spec )) {
       die "Could not checkout package '" . $pkgname . "' Makefile\n" ;
   }

   $curdir = "$projroot/src/$pkgname" ;
   # install target makefile, and update package makefile
   if ( $type eq "bin" ) {
      &CTInstallMake( "$tool/lib/Makefile.bin.template",
		      "$curdir/Makefile.$tgtname" ) ;
      &CTInstallScanMake( "$curdir/Makefile" ) ;
   } elsif ( $type eq "a" ) {
      $fulltgtname = "lib" . $tgtname ;
      &CTInstallMake( "$tool/lib/Makefile.a.template",
		      "$curdir/Makefile.$tgtname" ) ;
      &CTInstallScanMake( "$curdir/Makefile" ) ;
   } elsif ( $type eq "so" ) {
      $fulltgtname = "lib" . $tgtname ;
      &CTInstallMake( "$tool/lib/Makefile.so.template",
		      "$curdir/Makefile.$tgtname" ) ;
      &CTInstallScanMake( "$curdir/Makefile" ) ;
   } elsif ( $type eq "ss" ) {
      &CTInstallMake( "$tool/lib/Makefile.ss.template",
		      "$curdir/Makefile.$tgtname" ) ;
      &CTInstallScanMake( "$curdir/Makefile" ) ;
   } elsif ( $type eq "foreign" ) {
      &CTInstallMake( "$tool/lib/Makefile.foreign.template",
		      "$curdir/Makefile.$tgtname" ) ;
      &CTInstallScanMake( "$curdir/Makefile" ) ;
   }

   $item = "$curdir/Makefile.$tgtname" ;
   if ( ! &CTCMMkelem( $item, $projname, $spec ) ) {
       die "Could not make a verioned element of the target makefile\n" ;
   }
}

print "You will want to edit Makefile, Makefile.install, and the target makefile(s)\n" ;
print "manually.  Also, do not forget to delta the Makefile, target Makefile, and\n" ;
print "directory when you are done.\n" ;
