#!/usr/bin/perl

#
# Copyright 2013 - Grégory Soutadé
#

sub usage {
    print "Convert csv contacts from Nokia Suite to vCard format\n\n";
    print "usage : csv2cvf.pl [-h|--help] filename [call prefix] [cell phone prefix]\n";
    print "call prefix is \"+33\" by default\n";
    print "cell phone prefix is set to 6 by default (06XXXXX...)\n";
}

sub get_phone {
    my ($f0, $f1, $call_prefix, $cell_phone_prefix) = @_;

    my $cell_phone = $fields[$f0];
    my $fix_phone = $fields[$f1];

    $cell_phone = "$call_prefix$2" if ($cell_phone =~ /^(0)([0-9]+)/);
    $fix_phone = "$call_prefix$2" if ($fix_phone =~ /^(0)([0-9]+)/);

    if ($cell_phone eq "" && substr($fix_phone, 3, 1) eq $cell_phone_prefix)
    {
	$cell_phone = $fix_phone;
	$fix_phone = "";
    }

    return ($cell_phone, $fix_phone);
}

my $size = scalar(@ARGV);

if ($size == 0 || $size > 2)
{
    usage();
    exit();
}

my ($filename, $call_prefix, $cell_phone_prefix) = @ARGV;

if ($filename =~ "-h" || $filename =~ "--help")
{
    usage();
    exit();
}

my $call_prefix = "+33" if ($call_prefix eq "");
my $cell_phone_prefix = "6" if ($cell_phone_prefix eq "");

exit(1) if ( ! open(FIC,"<$filename") );

LINE : while( defined( $l = <FIC> ) ) {
   chomp $l;
   # First line are titles
   next LINE if ($. == 1);
   # print "$. : $l\n";

   @fields = split(/;/, $l);

   @fields = map { my @f = split(/"/, $_) ; $f[1] ;} @fields;

   $first_name = $fields[1];
   $last_name = $fields[3];

   if ($first_name eq "")
   {
       next LINE if ($last_name eq "");
       $name = $last_name;
   }
   else
   {
       if ($last_name eq "")
       {
	   $name = $first_name;
       }
       else
       {
	   $name = "$first_name $last_name";
       }
   }

   $email = $fields[15];

   open (VCF,">$name.vcf");

   print "Create \"$name.vcf\"\n";

   print VCF "BEGIN:VCARD\n";
   print VCF "VERSION:3.0\n";
   print VCF "N:$last_name;$first_name\n";
   print VCF "FN:$name\n";
   print VCF "EMAIL;TYPE=PREF,INTERNET:$email\n" if (! $email eq "");

   # General section
   ($cell_phone, $fix_phone) = get_phone(13, 14, $call_prefix, $cell_phone_prefix);
   print VCF "TEL;TYPE=voice,home:$fix_phone\n" if (! $fix_phone eq "");
   print VCF "TEL;TYPE=voice,cell,pref:$cell_phone\n" if (! $cell_phone eq "");

   # Personal section
   ($cell_phone, $fix_phone) = get_phone(27, 28, $call_prefix, $cell_phone_prefix);
   print VCF "TEL;TYPE=voice,home,pcs:$fix_phone\n" if (! $fix_phone eq "");
   print VCF "TEL;TYPE=voice,cell,pcs:$cell_phone\n" if (! $cell_phone eq "");

   # Work section
   ($cell_phone, $fix_phone) = get_phone(41, 42, $call_prefix, $cell_phone_prefix);
   print VCF "TEL;TYPE=voice,home,work:$fix_phone\n" if (! $fix_phone eq "");
   print VCF "TEL;TYPE=voice,cell,work:$cell_phone\n" if (! $cell_phone eq "");

   print VCF "END:VCARD";

   close (VCF);
}

close( FIC );
