#!/usr/bin/perl
# File to change a google contact csv to mutt alias list.
use warnings;
use strict;

#first thing to do is to convert google file that is encoded in UTF-16 Little Endian
my @args =  ("iconv","-f UTF-16","-o test.out","google.csv");
system @args == 0 or die "Call to system @args failed with $? !";
open(my $csv, "<", "test.out") or die "Cannot open test.out in this directory.";
open(my $output, ">", "aliases_file.txt") or die "Cannot open aliases_file.txt.";

my $first_line = <$csv>;
my @splitted_head = split(/,/, $first_line);
my $name_index = 0;
my $email_index = 0;
my $index = 0;

foreach (@splitted_head) {
    $name_index = $index if $_ eq "Name";
    $email_index = $index if $_ eq "E-mail 1 - Value";
    $index ++;
}

my $current_name = "";
my $current_email = "";
my $current_alias = "";
my @used_alias;
my $used_alias_index=0;


while (<$csv>) {
    my @splitted_line = split(/,/, $_);
    my $alias_counter = 1;
    $current_name =  $splitted_line[$name_index];
    $current_email = $splitted_line[$email_index];
    $current_name = $current_email if $current_name eq "";
    $current_name =~ s/@.*$// if $current_name =~ /@/;
    $current_alias = $current_name;
    $current_alias =~ s/\s\s*/./g;

    while (isAliasPresent($current_alias, @used_alias)) {
        $current_alias = "$current_alias"."$alias_counter";
        $alias_counter++;
    }
    push(@used_alias, $current_alias);
    
    print ($output "alias $current_alias $current_name <$current_email>\n") unless !$current_email;
}

close ($csv);
close ($output);

sub isAliasPresent {
    my ($alias, @alias_list) = @_;
    my $match = 0;

    $match = grep(/$alias/, @alias_list);

    return $match > 0;
}


