#!/usr/bin/perl
#
# convert old brinance files to new format
#  takes arg of where account/future files are and puts new file out to STDOUT

use warnings;
use strict;

my $account_dir;
if ($ARGV[0]) {
	$account_dir = $ARGV[0];
} else {
	$account_dir = "$ENV{HOME}/.brinance";
}

mkdir "$account_dir/archive";

my @lines;
my @names;
foreach ( glob ("$account_dir/account[0-9]*") ) {
	my $filename = $_;
	open ( FILE, $filename ) or die "ERROR: Could not open $_";
	/.*\/account(\d+)/;
	my $account_number = $1;

	my $date = "";
	my $comment = "";
	my $amount = 0;
	my $nameset = 0;
	while (<FILE>) {
		chomp;
		if (/^\s*#NAME: (.+)$/) {
			push (@names, "ACCOUNT $account_number: $1");
			$nameset = 1;
		}
		elsif (!$date and /^#(\d{12})$/) {
			$date = $1;
		}
		elsif ($date and !$comment and /^#(.+)$/) {
			$comment = $1;
		}
		elsif ($date and $comment and !$amount) {
			$amount = $_;

			push (@lines, "$date\t$account_number\t$amount\t$comment");
			$date = "";
			$comment = "";
			$amount = 0;
		}
		else {
			print STDERR "ERROR: $filename invalid at $_\n";
		}
	}
	close FILE;

	open ( FUTURE, "$account_dir/future$account_number" ) or die "ERROR: Could not open future$account_number";
	$date = "";
	$comment = "";
	$amount = 0;
	while (<FUTURE>) {
		chomp;
		if (/^\s*#NAME: (.+)$/) {
			if ($nameset) {
				next; # we already have the names
			}
			else {
				push (@names, "ACCOUNT $account_number: $1");
				$nameset = 1;
			}
		}
		elsif (!$date and /^#(\d{12})$/) {
			$date = $1;
		}
		elsif ($date and !$comment and /^#(.+)$/) {
			$comment = $1;
		}
		elsif ($date and $comment and !$amount) {
			$amount = $_;

			push (@lines, "$date\t$account_number\t$amount\t$comment");
			$date = "";
			$comment = "";
			$amount = 0;
		}
		else {
			print STDERR "ERROR: future$account_number invalid at line $.\n";
		}
	}
	close FUTURE;

	unless ($nameset) {
		push (@names, "ACCOUNT $account_number");
	}

	if (link ("$account_dir/account$account_number", "$account_dir/archive/$filename") ) {
		unlink ("$account_dir/account$account_number");
	}
	if (link ("$account_dir/future$account_number", "$account_dir/archive/future$account_number") ) {
		unlink ("$account_dir/future$account_number");
	}
}

@names = sort @names;
@lines = sort @lines;

open (ACCOUNTS, ">$account_dir/accounts") or die "ERROR: cannot create accounts file";

foreach (@names, @lines) {
	print ACCOUNTS "$_\n";
}
close ACCOUNTS;

print "If there are no errors above, the conversion was successful and you are ready to run brinance v4.\n";
print "Your old account files were put in $account_dir/archive\n";
