#!/usr/local/bin/perl

if ($#ARGV != 0) {
   exit print "Usage: ctaddpkg package-name\n" ;
}

$pkgname = $ARGV[0] ;

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

#pull in tools for getting information on the project
require "$tool/include/ctproj.pl" ;
require "$tool/include/ctvspec.pl" ;
require "$tool/include/ctquery.pl" ;

#get what project we're currently in, and where it's root is.
$proj = &CTProj ;
$projroot = &CTProjRoot($proj) ;
$projname = $proj ;
$projname =~ tr/A-Z/a-z/ ;
$flav = &CTQueryProj( $projname ) ;
$spec = &CTResolveSpec( $projname, $flav ) ;

#see if such a package already exists, if so STOP
if ( -e "$projroot/src/all/$pkgname" ) {
   die "Package '$pkgname' already exists in this project ('$proj')" ;
}

#make sure there is a project-wide makefile
if ( ! -e "$projroot/Makefile" ) {
   die "No project-wide Makefile for project '$proj'" ;
}

#make sure there is a package Makefile template
if ( ! -e "$tool/lib/Makefile.meta.template" ) {
   die "No package Makefile template in $tool/lib/." ;
}

#make sure there is a package install Makefile template
if ( ! -e "$tool/lib/Makefile.install.template" ) {
   die "No package install Makefile template in $tool/lib/." ;
}

#make the package directory
require "$tool/include/ctcm.pl" ;
$item = "$projroot/src/all/$pkgname" ;
if ( ! -e $item ) {
    if ( ! &CTCMMkdir( $item, $projname, $spec ) ) {
	die "Could not create directory '" . $item . "'\n" ;
    }
}

#pull in tools for installing Makefiles
require "$tool/include/ctinstmake.pl" ;

#install a package makefile and package install makefile into the package
$item = "$projroot/src/all/$pkgname/Makefile" ;
&CTInstallMake( "$tool/lib/Makefile.meta.template", $item ) ;
if ( ! &CTCMMkelem( $item, $projname, $spec ) ) {
    die "Could not make a verioned element of the project makefile\n" ;
}
if ( ! &CTCMDelta( $item, $projname, $spec ) ) {
    die "Could not delta '" . $item . "'\n" ;
}

$item = "$projroot/src/all/$pkgname/Makefile.install" ;
&CTInstallMake( "$tool/lib/Makefile.install.template", $item ) ;
if ( ! &CTCMMkelem( $item, $projname, $spec ) ) {
    die "Could not make a verioned element of the project install makefile\n" ;
}
if ( ! &CTCMDelta( $item, $projname, $spec ) ) {
    die "Could not delta '" . $item . "'\n" ;
}

# delta the package in
$item = "$projroot/src/all/$pkgname" ;
if ( ! &CTCMDelta( $item, $projname, $spec ) ) {
    die "Could not delta '" . $item . "'\n" ;
}

# update the master makefile
$item = "$projroot/Makefile" ;
if ( ! &CTCMCheckout( $item, $projname, $spec ) ) {
    die "Could not checkout master project makefile\n" ;
}
&CTInstallScanMake( $item ) ;
if ( ! &CTCMDelta( $item, $projname, $spec ) ) {
    die "Could not delta master project makefile\n" ;
}
