#! /usr/local/bin/perl
#
# Elm
#
# <handle> = <last>; <first>, <comment> = <addr>
#
# Mutt
#
# alias <handle> <addr> (<first> <last>)
#
# 1.1    15/07/96       first version
# 1.2    06/09/96       Eurocontrol-specific alias generation
#                       use extended RE
# 1.3    07/11/96       handle group aliases

require 5.003;

use FileHandle;
use File::Basename;

## Config.
##
my $elm_dir    = "$ENV{'HOME'}/.elm";
my $elm_alias  = "$elm_dir/aliases.text";
my $mutt_alias = "$elm_dir/mail_aliases";
my $grp_alias  = "$elm_dir/group_aliases";

my $prog_name = basename ($0);
my $cnt = 0;                            # normal alias count
my $grp_cnt = 0;                        # Group alias count

## Open files
##
my $fh_in = FileHandle->new ("<$elm_alias");

die "Can't open $elm_alias\n"
    if (!defined $fh_in);

my $fh_out = FileHandle->new (">$mutt_alias");

die "Can't open $mutt_alias\n"
    if (!defined $fh_out);

my $fh_grp = FileHandle->new (">$grp_alias");

die "Can't open $grp_alias\n"
    if (!defined $fh_grp);

## Output banner in Mutt alias file
##
print $fh_out <<"EOF";
## $mutt_alias
## Converted by $prog_name, v1.3 from aliases.text
##
## Ollivier Robert
##
EOF

print $fh_grp <<"EOF";
## $group_alias
## Converted by $prog_name, v1.3 from aliases.text
##
## Group addresses ONLY
##
## Ollivier Robert
##
EOF

## Convert
##
while (<$fh_in>)
{
    chomp;
    ## Skip comments and blank lines
    ##
    next if (/^#/o or /^$/o);

    ## Split
    ##
    my ($handle, $full_info, $addr) = split (/\s*=\s*/o);
    my ($last, $first, $comment) = split (/[,;]/o, $full_info);

    ## Skip leading blanks
    ##
    $first   =~ s,\G ,,g;
    $last    =~ s,\G ,,g;
    $comment =~ s,\G ,,g;

    ## Output converted aliases
    ##
    if ($addr =~ /,/)
    ## We have a group
    ##
    {        
        $fh_grp->print ("# Info: $comment\n");
        $fh_grp->print ("alias $handle $addr\n");
        $grp_cnt++;
    }
    else
    {
        $fh_out->print ("# Info: $comment\n");
        $fh_out->print ("alias $handle $first $last <$addr>\n");
        $cnt++;
    }
}
$fh_in->close;
$fh_out->close;

my $total_cnt = $cnt + $grp_cnt;

print <<"EOF";
Read $total_cnt aliases...
$cnt\tregular aliases converted.
$grp_cnt\tGroup aliases converted.
EOF
