#!usr/bin/perl -w

#
#  This script imports forwarders into CGPro domain.
#  The import file should contain multiline TAB-delimeted list of
#  forwarder names and their destination addresses, e.g:
#
#   user1<TAB>user1@some.domain.com<EOL>
#   user2<TAB>user@other.domain.com<EOL>
#
#

use CLI;                  # make sure the CLI.pm is in the current directory

# Check the program's arguments
if(@ARGV<1) {
  print "Usage: ImportForwarders.pl ForwardersFile.txt\n";
  exit;
}

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";


my $lineNum=0;
my $nAdded=0;

while(<>) {                                       # read a line from the input file
  chomp($_);                                      # remove the \n from the line
  $lineNum++;
  my ($name,$forwardTo) = (split(/\t/));          # extract forwarder name and the address
  
  next if(!defined $name || $name eq '');         # skip if it was empty line
  
  if(!defined $forwardTo || $forwardTo eq '') {   # report if there was a file format error
    print "Line $lineNum: Error in input file format: $_\n";

  } else {
    $name.="\@$Domain"; # add the domain so you could specify forwarders for secondary domains

    if($cli->CreateForwarder($name,$forwardTo)) {
      $nAdded++;
    } else {
      print "Line $lineNum: $name->$forwardTo; ".$cli->getErrMessage."\n";
    }
  }
}
print " $nAdded forwarders added into $Domain domain.\n";
$cli->Logout;

