#!/usr/bin/perl

use Data::Dump 'dump';

#get commandline arguments
my $arg_hash;
foreach my $arg (@ARGV) {
	my ($param, $value) = split /\=/, $arg;
	if (!defined($value)) {
		$value = $param;
	}
	$arg_hash->{$param} = $value;
}

#conversion
if (defined($arg_hash->{'--s2p'})) {#convert from s25@once to Phonebackup
	if (defined($arg_hash->{'--s25'})) {#argument passed
		if (!defined($arg_hash->{'--pb'})) {#no argument passed
			$arg_hash->{'--pb'} = ($arg_hash->{'--s25'} =~ /^(.*)\..*?$/i)[0].'.ms';
			print "No target file specified. Using $arg_hash->{'--pb'}\n";
		}
		my $input = &read_file($arg_hash->{'--s25'});
		my $output;
		if (defined $input) {#file read
			#s25@once CSV Format: Firstname;Lastname;Company;Street Nr;ZIP Code;City;Country;[Private Phone] || Private Phone;[Office];[Mobile];[Fax];email;Website
			#Phonebook VCard Format: <Contact Value=BEGIN:VCARD<br/>VERSION:2.1<br/>N:$name<br/>TEL;WORK:$office<br/>TEL;HOME:$private<br/>EMAIL;INTERNET;PREF:$email<br/>TEL;CELL:$mobile<br/>TEL;FAX:$fax<br/>ORG:$company<br/>END:VCARD/>\r\n
			$output .= "<Contacts>\r\n";
			my $count = 0;
			foreach my $contact (split /\r?\n/, $input) {
				if ($count == 0) { $count++; next; }# Skip first entry
				my ($firstname, $lastname, $company, $street_nr, $zip_code, $city, $country, $private, $office, $mobile, $fax, $email, $website) = split /[,;]/, $contact;
				$private = ($private =~ /^\[(.*)\]$/ ? $1 : $private);#remove []
				$office  = ($office  =~ /^\[(.*)\]$/ ? $1 : $private);#remove []
				$mobile  = ($mobile  =~ /^\[(.*)\]$/ ? $1 : $private);#remove []
				$fax     = ($fax     =~ /^\[(.*)\]$/ ? $1 : $private);#remove []
				my $name;
				if (defined($arg_hash->{'--s25lf'})) {#s25: Lastname, Firstname
					$name = "$lastname;$firstname";
				} else {#s25: Firstname Lastname
					($firstname, $lastname) = split / /, $firstname.$lastname;
					(!defined($lastname)) && ($lastname = '');
					$name = "$lastname;$firstname";
				}
				my $line = "   <Contact Value=BEGIN:VCARD<br/>VERSION:2.1<br/>";
				#begin data
				if ($name)    {
					if ($name =~ /[ÄäÖöÜüßÉéÈèÁáÀà]/) {#enconde
						my @tr = qw(=C4 Ä =E4 ä =D6 Ö =F6 ö =DC Ü =FC ü =DF ß =C1 Á =E1 á =C0 À =E0 à =C9 É =E9 é =C8 È =E8 è);
						for (my $i = 0; $i < @tr; $i++) {
							$name =~ s/$tr[$i+1]/$tr[$i]/g;
							$i++;
						}
				 		$line .= "N;ENCODING=QUOTED-PRINTABLE:$name<br/>";
					} else {
						$line .= "N:$name<br/>";
					}
				} #Name
				if ($office)  { $line .= "TEL;WORK:$office<br/>"; } #office phone
				if ($private) { $line .= "TEL;HOME:$private<br/>"; } #private phone
				if ($email)   { $line .= "EMAIL;INTERNET;PREF:$email<br/>"; } #email
				if ($mobile)  { $line .= "TEL;CELL:$mobile<br/>"; } #mobile phone
				if ($fax)     { $line .= "TEL;FAX:$fax<br/>"; } #fax
				if ($company) { $line .= "ORG:$company<br/>"; } #company
				#end data
				$line .= "END:VCARD/>\r\n";
				$output .= $line;
				$count++;
			}
			$output .= "</Contacts>\r\n";
			#print $output;
			print "Converted $count Contacts\n";
			if (&write_file($arg_hash->{'--pb'}, $output)) {
				print "File $arg_hash->{'--pb'} written\n";
			} else {
				print "Error: Couldn't write file $arg_hash->{'--pb'}!\n";
			}
		} else {#error
			print "Error while reading input file  $arg_hash->{'--s25'}!\n";
			exit 1;
		}
	} else {#no argument passed
		print "Error: you must specify the s25\@once input file!\n";
		exit 1;
	}
} elsif (defined($arg_hash->{'--p2s'})) {#convert from Phonebackup to s25@once
	if (defined($arg_hash->{'--pb'})) {#argument passed
		if (!defined($arg_hash->{'--s25'})) {#no argument passed
			$arg_hash->{'--s25'} = ($arg_hash->{'--pb'} =~ /^(.*)\..*?$/i)[0].'.csv';
			print "No target file specified. Using $arg_hash->{'--s25'}\n";
		}
		my $input = &read_file($arg_hash->{'--pb'});
		my $output;
		if (defined $input) {#file read
			#s25@once CSV Format: Firstname;Lastname;Company;Street Nr;ZIP Code;City;Country;[Private Phone] || Private Phone;[Office];[Mobile];[Fax];email;Website
			#Phonebook VCard Format: <Contact Value=BEGIN:VCARD<br/>VERSION:2.1<br/>N:$name<br/>TEL;WORK:$office<br/>TEL;HOME:$private<br/>EMAIL;INTERNET;PREF:$email<br/>TEL;CELL:$mobile<br/>TEL;FAX:$fax<br/>ORG:$company<br/>END:VCARD/>\r\n
			$output .= "Vorname;Nachname;Firma;Strasse;PLZ;Ort;Land;Tel. privat;Tel. geschäftl.;Tel. Handy;Fax;eMail;URL\r\n";
			my $count = 0;
			foreach my $contact (split /\r?\n/, $input) {
				if (!($contact =~ /\<Contact /)) { $count++; next; }# Skip non contact entry
				my ($firstname, $lastname, $office, $private, $email, $mobile, $fax, $company) = ('', '', '', '', '', '', '', '');
				foreach my $item (split /\<br\/\>/, $contact) {
					if ($item =~ /^N\:(.*)\;(.*)$/i) {
						$lastname  = $1;
						$firstname = $2;
					}
					if ($item =~ /^N\;ENCODING\=QUOTED\-PRINTABLE\:(.*)\;(.*)$/i) {
						$lastname  = $1;
						$firstname = $2;
						my @tr = qw(=C4 Ä =E4 ä =D6 Ö =F6 ö =DC Ü =FC ü =DF ß =C1 Á =E1 á =C0 À =E0 à =C9 É =E9 é =C8 È =E8 è);
						for (my $i = 0; $i < @tr; $i++) {
							$lastname  =~ s/$tr[$i]/$tr[$i+1]/g;
							$firstname =~ s/$tr[$i]/$tr[$i+1]/g;
							$i++;
						}
					}
					if ($item =~ /^TEL\;WORK\:(.*)$/i)             { $office  = $1; }
					if ($item =~ /^TEL\;HOME\:(.*)$/i)             { $private = $1; }
					if ($item =~ /^TEL\;CELL\:(.*)$/i)             { $mobile  = $1; }
					if ($item =~ /^TEL\;FAX\:(.*)$/i)              { $fax     = $1; }
					if ($item =~ /^EMAIL\;INTERNET\;PREF\:(.*)$/i) { $email   = $1; }
					if ($item =~ /^ORG\:(.*)$/i)                   { $company = $1; }
				}
				if (!defined($arg_hash->{'--s25lf'})) {#s25: Firstname Lastname
					$lastname = $firstname.($firstname && $lastname ? ' ' : '').$lastname;
					$firstname = '';
				}
				print $contact."\n";
				print "$firstname;$lastname;$company;;;;;$private;$office;$mobile;$fax;$email;\r\n";
				$output .= "$firstname;$lastname;$company;;;;;$private;$office;$mobile;$fax;$email;\r\n";
				$count++;
			}
			#print $output;
			#print "Converted $count Contacts\n";
			#if (&write_file($arg_hash->{'--pb'}, $output)) {
			#	print "File $arg_hash->{'--pb'} written\n";
			#} else {
			#	print "Error: Couldn't write file $arg_hash->{'--pb'}!\n";
			#}				
		} else {#error
			print "Error while reading input file  $arg_hash->{'--pb'}!\n";
			exit 1;
		}
	} else {#no argument passed
		print "Error: you must specify the Phonebackup input file!\n";
		exit 1;
	}
} else {#help screen
	usage();
}

exit 0;

sub usage {
	print <<EOF;
About:
 This little script converts _Phonbook_ Backups done with
 s25\@once (http://www.s25atonce.de/ - Siemens mobile phones)
 to ones that may be read from Phonebackup
 (http://www.christersson.org/software.php - SonyEricsson mobiles)
 and vice versa.
 It should accept and write .csv backups from s25\@once and
 .ms backups from Phonebackup.
 It's a quick hack poorly tested with the ME45 and the T610, so
 use it at your own risk.

Usage:
 contact_converter_s25atonce_phonebackup.pl [OPTIONS]
 --help         This screen
 --s2p          Read from s25\@once file and write to phonebackup file
 --p2s          Read from phonebackup file and write to s25\@once file
 --s25=FILE.csv The s25\@once FILE
 --pb=FILE.ms   The cristersson.org phonebackup FILE
 --s25lf        Contact names in the s25\@once file are stored in
                "Lastname, Firstname" order instead of "Firstname Lastname"
 
2003 by streawkceur (twittek\@smail.uni-koeln.de)
EOF
}

sub read_file {
	my $filename = shift;

	if (-e $filename) {
		open(FILE, $filename);
		local($/) = undef;
		my ($file) = <FILE>;
		close(FILE);
		return $file;
	} else {
		return undef;
	}
}

sub write_file {
	my $filename = shift;
	if (!open(FILE, ">$filename")) {
		return 0;
	}
	print FILE @_;
	close(FILE);
	return 1;
}
