#!/usr/bin/perl -w
#
# This script does the opposite thing to the "Import Accounts"
# from the Web interface.
# <http://old.communigatepro.ru/CommuniGatePro/Accounts.html#Loader>
#
# It may be useful if by mistake you've imported an acount list
# into a wrong domain.
#

use CLI;

# Check the program's arguments
if(@ARGV!=1) {
  print "Usage: DeleteAccounts.pl AccountsFile\n";
  print "See <http://old.communigatepro.ru/CommuniGatePro/Accounts.html#Import> about the AccountsFile format\n";
  exit;
}


# Read first string form ARGV[0] file into $_
# Split $_ into array by TABs, so @fieldList should contain field names
@fieldList = split(/\t/,<>);


# Find the column that contains account name
#
my $NameIndex =0;
foreach (@fieldList) {   # Check all field names
  if(/Name/i) {       # Break if fieldList[NameIndex]=="Name"
    last;
  }
  ++$NameIndex;
}

if($NameIndex >= @fieldList) {  # We didn't find "Name" field
  die "The accounts file doesn't contain 'Name' field\n";
}

print "Domain: ";         # Print the domain prompt
my $Domain = <STDIN>;     # Read the domain name from standard input
chomp $Domain;            # Remove \n if present

# You may need to redefine the following variable if you're connecting not to
# the main domain. IP address is OK.
$CGServerAddress = $Domain;

print "Login (Enter for \"Postmaster\@$Domain\"): ";
my $Login = <STDIN>;
chomp $Login;
if ($Login eq '') { $Login = "Postmaster\@$Domain"; }

print "Password: ";
my $Password = <STDIN>;
chomp $Password;

# Open TCP connection to given address port 106 (PWD, or CGPro CLI).
# Submit username and password. If login fail, the program will stop.
my $cli = new CGP::CLI( { PeerAddr => $CGServerAddress,
                          PeerPort => 106,
                          login    => $Login,
                          password => $Password } )
   || die "Can't login to CGPro: ".$CGP::ERR_STRING."\n";


# Read the rest of the lines from ARGV[0]
# From each line extract the account name and delete the account.
while(<>) {
  my ($UserName) = (split(/\t/))[$NameIndex];
  chomp($UserName);
  if($cli->DeleteAccount("$UserName\@$Domain")) {
    print "Account \"$UserName\@$Domain\" deleted.\n";
  } else {
    print "Unable to delete \"$UserName\@$Domain\": ".$cli->getErrMessage."\n";
  }
}

$cli->Logout;
