#!/usr/bin/perl
# dia2vcf - dia to vCard converter
# Done 2007 by Jonas Mitschang, jonen@mitschang.net
#
# This script converts DIA address book files (e.g. generated by MobilEDIT)
# to the vCard format
# The vCard format can be easily imported by most organizer tools.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# If you improve this script, please send me a copy.
#
# Usage:
#   cat foo.dia | dia2vcf > foo.vcf
#
use strict;

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

# program usage
sub usage {
    printf "Usage: cat foo.dia | dia2vcf > foo.vcf\n";
    exit 0;
}

# parameter supplied? show usage
&usage if $ARGV[0];

# 20061109T231130Z
chomp(my $dtstamp = `date +%Y%m%dT%H%M%SZ`);


# process all lines from standard input
my $count = 0;
my ($id, $name, $email, @tel, $mobile);
while (<>) {
    # remove \n and skip empty lines
    chomp;
    s/\r//;
    next unless $_;

    my ($_id, $_name, $data) = split /\t/;
    if ($_id ne $id) {
        writeActual();
        # new contact
        ($id, $name, $mobile, $email) = ($_id, $_name, , );
        @tel = ();
    }

    malformed() if $_name ne $name;

    if ($name ne $data) {
        if (!$mobile and ($data =~ /^(\+49|00|0)1\d+$/)) {
            $mobile = $data;
        } elsif ($data =~ /^\+?\d+$/) {
            push @tel, $data;
        } elsif ($data =~ /^.*\@.*/) {
            $email = $data;
        } else {
            printf STDERR "Warning: Unknown data for $name: '$data'. Ignoring.\n";
        }
    }

}
writeActual();

# status message to stderr
printf STDERR "Processed $count vCards\n";


# Source file is malformed. Stop execution
sub malformed {
    die "Source malformed.\n";
}

# Print current contact
sub writeActual() {
    $count++;

    printf <<EOF;
BEGIN:VCARD
CLASS:PUBLIC
EOF
    printf "EMAIL:$email\n" if $email;
    printf "FN:$name\n";
    #N:Mueller;Peter;;;

    printf "TEL;TYPE=MOBILE:$mobile\n" if $mobile;
    foreach my $t (@tel) {
        printf "TEL:$t\n";
    }

    print <<EOF;
VERSION:3.0
END:VCARD

EOF
                
}

