#!/usr/bin/perl

# This little program, as sloppy as it is, is copyright by Trevor
# Jorgenson (trevor@totalweb.net).  There is no warrenty, expressed or
# implied and you are solely responsible if anything happens to your
# system by running this program.  Please take the time to review the code
# and make any changes that you need to.

# Please read the "README" file for more information.

$mailpath = "/var/spool/mail";

# Check arguments
if ($ARGV[0] eq "") { &usage; }

# Extract home directory from passwd
open(PASS, "/etc/passwd");
@passwd = <PASS>;
close(PASS);

$message = "Username $ARGV[0] not found.";
foreach(@passwd) {
  ($name, $pass, $uid, $gid, $fullname, $home, $shell) = split(/:/);
  if ($name eq $ARGV[0]) { 
$message = ""; 
$directory = $home; 
$group = $gid;
                         }
}

if ($message ne "") { &error; }

# Remove home directory
$null = `/bin/rm -rf $directory`;
print "MESSAGE: Home directory removed.\n";

# Remove mailbox
unlink("$mailpath/$ARGV[0]") || die "ERROR: Couldn't remove mailbox.\n";
print "MESSAGE: Mailbox removed.\n";

# Remove entries from group file
open(GROUP, "/etc/group") || die "ERROR: Couldn't open group file.\n";
@group = <GROUP>;
close(GROUP);

$remove = `/bin/grep "^$ARGV[0]:" /etc/group`;

foreach(@group) {
   s/$remove//;
}

foreach(@group) {
   s/,$ARGV[0]//g;
}

foreach(@group) {
   s/:$ARGV[0],/:/g;
}

open(GROUP, ">/etc/group");
print GROUP @group;
close(GROUP);
print "MESSAGE: Group entry removed.\n";

# Remove entry from password file

$remove1 = `/bin/grep "^$ARGV[0]:" /etc/passwd`;

foreach(@passwd) {
 s/$remove1//;
}

open(PASSWD, ">/etc/passwd");
print PASSWD @passwd;
close(PASSWD);
print "MESSAGE: Passwd entry removed.\n";

sub usage {
  print "USAGE: deluser <USERNAME>\n";
  exit 1;
}

sub error {
  print "ERROR: $message\n";
  exit 1;
}
