#!/usr/bin/perl -w

use strict;
use vars qw($opt_h);
use Fcntl qw(:flock);
use Getopt::Std;

my $FREESIDE_CONF = "%%%FREESIDE_CONF%%%";

getopts("h:");
my $user = shift or die &usage;

if ( $opt_h ) {
  open(HTPASSWD,"<$opt_h")
    and flock(HTPASSWD,LOCK_EX)
      or die "can't open $opt_h: $!";
  open(HTPASSWD_TMP,">$opt_h.tmp") or die "can't open $opt_h.tmp: $!";
  while (<HTPASSWD>) {
    print HTPASSWD_TMP $_ unless /^$user:/;
  }
  close HTPASSWD_TMP;
  rename "$opt_h.tmp", "$opt_h" or die $!;
  flock(HTPASSWD,LOCK_UN);
  close HTPASSWD;
}

open(MAPSECRETS,"<$FREESIDE_CONF/mapsecrets")
  and flock(MAPSECRETS,LOCK_EX)
    or die "can't open $FREESIDE_CONF/mapsecrets: $!";
open(MAPSECRETS_TMP,">>$FREESIDE_CONF/mapsecrets.tmp")
  or die "can't open $FREESIDE_CONF/mapsecrets.tmp: $!";
while (<MAPSECRETS>) {
  print MAPSECRETS_TMP $_ unless /^$user\s/;
}
close MAPSECRETS_TMP;
rename "$FREESIDE_CONF/mapsecrets.tmp", "$FREESIDE_CONF/mapsecrets" or die $!;
flock(MAPSECRETS,LOCK_UN);
close MAPSECRETS;

sub usage {
  die "Usage:\n\n  freeside-deluser [ -h htpasswd_file ] username"
}

=head1 NAME

freeside-deluser - Command line interface to add (freeside) users.

=head1 SYNOPSIS

  freeside-deluser [ -h htpasswd_file ] username

=head1 DESCRIPTION

Adds a user to the Freeside billing system.  This is for adding users (internal
sales/tech folks) to the web interface, not for adding customer accounts.

  -h: Also delete from the given htpasswd filename

=head1 SEE ALSO

L<freeside-adduser>, L<htpasswd>(1), base Freeside documentation

=cut

