#!/usr/perl5/bin/perl
#
# Copyright (c) 1999 by Sun Microsystems, Inc.
# All rights reserved.
#
#ident	"@(#)projdel.pl	1.1	00/02/14 SMI"
#

require 5.005;
use strict;
use locale;
use English;
use FileHandle;
use File::Basename;
use Getopt::Std;
use POSIX qw(locale_h);
use Sun::Solaris::Utils qw(textdomain gettext);

sub usage(@)
{
	my (@msg) = @_;
	print STDERR basename($0), ": @msg\n" if (@msg);
	print STDERR gettext("Usage: projdel project\n");
	exit(2);
}

setlocale(LC_ALL, "");
textdomain("SUNW_OST_OSCMD");

my %opts = ();
getopts("", \%opts) || usage();

my $project = $ARGV[0];

my $project_file = "/etc/project";

# if not root, msg and exit
usage(gettext("ERROR: you must be root to administer projects"))
    if ($EUID != 0);

usage(gettext("ERROR: you must specify a project name"))
    unless defined $ARGV[0];

#
# Open the existing local database and the modified version.
#
my $original_fh;
my $new_fh;

$new_fh = new FileHandle "$project_file.tmp", O_WRONLY | O_EXCL | O_CREAT;
if (!defined($new_fh)) {
	printf STDERR "projdel: %s\n", $ERRNO;
	unlink "$project_file.tmp";
	exit(1);
}

#
# For projdel, the absence of /etc/project is fatal.
#
$original_fh = new FileHandle "$project_file", O_RDONLY;
if (!defined($original_fh)) {
	printf STDERR "projdel: %s\n", $ERRNO;
	unlink "$project_file.tmp";
	exit(1);
}
	
my $deleted = 0;
while (<$original_fh>) {
	my ($this_project, $this_projid, $this_comment, $these_users,
	    $these_groups, $these_attributes) = split(/:/);

	if ($this_project eq $project) {
		$deleted++;
		next;
	}

	$new_fh->print($_);
}

if ($deleted == 0) {
	printf STDERR gettext("projdel: no such project \"%s\"\n"), $project;
	unlink "$project_file.tmp";
	exit(1);
}

rename("$project_file.tmp", $project_file);

exit(0);
