#!/usr/bin/perl

use strict;
use warnings;

# addressbook.pl - build squirrelmail address book list
# Copyright (C) 2006, ed neville
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# changelog
#
# 20060116 ewn very alpha code


my %hashtable;

sub trim( $ )
{
  my $str = shift;
  $str =~ s/^\s+//;
  $str =~ s/\s+$//;
  return( $str );
}

sub removeangle( $ )
{
  my $str = shift;
  $str =~ s/^<//;
  $str =~ s/>$//;
  return( $str );
}

sub removequotes( $ )
{
  my $str = shift;
  $str =~ s/^("|')//;
  $str =~ s/("|')$//;
  return( $str );
}

sub parsefile( $ )
{
  my $filename = shift;
  if( ! -f $filename )
  {
    return;
  }
  open( F, $filename );
  my @lines = <F>;
  close( F );
  foreach my $line ( @lines )
  {
    if( $line =~ /^(To|From):(.*)(<.+\@.+>)$/ )
    {
      my @parts = split / /, removequotes( trim( $2 ) );
      my $len = scalar( @parts );
      my $email = removeangle( trim( $3 ) );
      if( defined( $hashtable{$email} ) )
      {
        return;
      }
      print( ( $len>0 ? "$parts[0]" : "" ) . "|" );
      print( ( $len>1 ? "$parts[1]" : "" ) . "|" );
      print( ( $len>2 ? "$parts[2]" : "" ) . "|" );
      print( "$email|\n" );
      
      # print "$email\n";
      $hashtable{$email} = 1;
      next;
    }
    if( $line =~ /^(To|From):(.+\@.+)$/ )
    {
      my $email = removeangle( removequotes( trim( $2 ) ) );
      if( defined( $hashtable{$email} ) )
      {
        return;
      }
      print "|||$email|\n";
      $hashtable{$email} = 1;
    }
    
  }
}

my $pathname = "/home/ed/nfs/Maildir/cur/";
opendir( M, $pathname );
my @files = readdir( M );
foreach my $path ( @files )
{
  parsefile( "$pathname$path" );
}
closedir( M );



