#!/usr/bin/perl
#
# Conversion vcf > txt (vcard to plain text).
#
# $Id       : vcf2txt.pl $
# $HeadURL  : http://bobotig.fr/contenu/contrib/scripts/vcf2txt.pl $
# $Source   : http://bobotig.fr/contenu/contrib/scripts/vcf2txt.pl $
# $Author   : BoboTiG $
# $Revision : 0 $
# $Date     : 2011/03/16 $
#

use strict;
use warnings;
use 5.010;
use autodie qw(close);

# Fonction
sub usage {
	say 'Usage : perl vcf2txt.pl <input file> [<output file>]';
	exit 0;
}

# Variables
our $VERSION = '0.1';
my $input = shift || usage();
my $output = shift || $input;
my @data_out;
my @data_in;
my @head;
my $version = 0;
my $rev = 0;
my $total = 0;

# C'est parti mon kiki !
say ' ~ vcf2txt v'.$VERSION.' { BoboTiG }';
say ' + Input file is "'.$input.'", working...';
$output = ( substr($input, -3) eq 'vcf' ?  substr($input, 0, length($input) - 3).'txt' : $input.'.txt' );
if ( open my $I, '<', $input ) {
	@{data_in} = <$I>;
	close $I;
} else {
	say ' ! Unable to open the input file "'.$input.'" !';
	exit 0;
}
foreach my $line ( @{data_in} ) {
	if ( ! $version ) {
		my ($v) = $line =~ m/^VERSION:(.*)/xms;
		if ( defined $v ) { push @{head}, 'VERSION:'.$v; $version = 1; next; }
	}
	if ( ! $rev ) {
		my ($r) = $line =~ m/^REV:(.*)/xms;
		if ( defined $r ) { push @{head}, 'REV:'.$r; $rev = 1; next; }
	}
	$line =~ s/=C3=A9/é/gxms;
	$line =~ s/=C3=AF/ï/gxms;
	$line =~ s/ENCODING=QUOTED-PRINTABLE;//xms;
	my ($name) = $line =~ m/N;CHARSET=UTF-8:;(.*)/xms;
	if ( defined $name ) { push @{data_out}, $name; next; }
	my ($num) = $line =~ m/TEL;HOME;CELL;CHARSET=UTF-8:(.*)/xms;
	if ( defined $num ) { push @{data_out}, $num; ++$total; next; }
}
foreach ( @{data_out} ) { $_ =~ s/(\r|\n)//gxms; }
foreach ( @{head} ) { $_ =~ s/(\r|\n)//gxms; }
say '   -> '.$total.' contacts found.';
if ( open my $O, '>', $output ) {
	print {$O} join("\n", @{head})."\n\n";
	for ( my $i = 0; $i < $#data_out; $i += 2 ) {
		print {$O} $data_out[$i].q{:}.$data_out[$i + 1]."\n";
	}
	close $O;
	say ' + Output file is "'.$output.'", I finished my homeworks.';
} else {
	say ' ! Unable to append the output file "'.$output.'" !';
	exit 0;
}
say ' ^ Ex(c)ting !';
exit 0;

