#!/usr/bin/perl

# $Header$

#######################################################################
#   list_folders.pl is called like this:                              #
#      ./list_folders.pl -S host/user/password -O <output file>       # 
#######################################################################

use Socket;
use FileHandle;
use Fcntl;
use Getopt::Std;
use IO::Socket;
use IMAP::Utils;

#################################################################
#################################################################

   init();

   connectToHost($sourceHost, \$src)   or exit;
   login($sourceUser,$sourcePwd, $src, $srcMethod) or exit;
   namespace( $src, \$srcPrefix, \$srcDelim, $opt_x );
   @mbxs = getMailboxList( $srcPrefix, $src, $mbxList, $opt_R);

   @mbxs = sort @mbxs;

   if ( $output_file ) {
      open(OUT, ">$output_file") or die "Can't open output file $output_file: $!";
      foreach $mbx ( @mbxs ) {
         print OUT "$mbx\n";
      }
      close OUT;
      Log ("Wrote list of mailboxes to $output_file\n");
      exit;
   }
   foreach $mbx ( @mbxs ) {
      print STDOUT "$mbx\n";
   }
 

   logout( $src );

   exit;


sub init {

   $os = $ENV{'OS'};

   processArgs();

   if ($timeout eq '') { $timeout = 60; }

   IMAP::Utils::init();
   #  Open the logFile
   #
   if ( $logfile ) {
      openLog($logfile);
   }
   Log("$0 starting");

   #  Set up signal handling
   $SIG{'ALRM'} = 'signalHandler';
   $SIG{'HUP'}  = 'signalHandler';
   $SIG{'INT'}  = 'signalHandler';
   $SIG{'TERM'} = 'signalHandler';
   $SIG{'URG'}  = 'signalHandler';

}

sub usage {

   print STDOUT "usage:\n";
   print STDOUT " iu-listfolders -S host/user/password -O <output file>\n";
   exit;

}

sub processArgs {

   if ( !getopts( "dS:L:hqt:vO:" ) ) {
      usage();
   }
   if ( $opt_S =~ /\\/ ) {
      ($sourceHost, $sourceUser, $sourcePwd,$srcMethod) = split(/\\/, $opt_S);
   } else {
      ($sourceHost, $sourceUser, $sourcePwd,$srcMethod) = split(/\//, $opt_S);
   }

   $logfile  = $opt_L;
   $timeout  = $opt_t;
   $debug    = 1 if $opt_d;
   $verbose  = 1 if $opt_v;
   $output_file   = $opt_O;
   $quiet_mode  = 1 if $opt_q;
   $timeout = 45 unless $timeout;

   usage() if $opt_h;

}

#  Handle signals

sub signalHandler {

my $sig = shift;

   if ( $sig eq 'ALRM' ) {
      Log("Caught a SIG$sig signal, timeout error");
      $conn_timed_out = 1;
   } else {
      Log("Caught a SIG$sig signal, shutting down");
      exit;
   }
   Log("Resuming");
}
