The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

use Cwd;
use File::HomeDir;
use File::Path;
use File::Slurp::Tiny qw(write_file);
use Finance::Bank::ID::BPRKS;
use YAML;

our $VERSION = '0.02'; # VERSION

# we don't use required=>1 because App::Options still works in BEGIN phase and
# thus breaks perl -c.

use App::Options (
    option => {
        profile   => { type => 'string', default => 'default' },
        account   => { type => 'string', default => "" },
        username  => { type => 'string' }, # req
        password  => { type => 'string' }, # req
        data_dir  => { type => 'string',   # req
                       default => File::HomeDir->my_home . "/bprks" },
        log_dir   => { type => 'string',   # req
                       default => File::HomeDir->my_home . "/bprks/logs" },
        days      => { type => 'string', default => 31 },
    },
);

use vars qw($Log_Level);
BEGIN { $Log_Level = "debug" }

use Log::Any::App '$log',
    -category_level => {Dumps=>'off'},
    -file           => {
        path           => "$App::options{log_dir}/main.log",
    },
    -dir            => {
        path           => "$App::options{log_dir}/dumps",
        level          => 'off',
        # currently we always dump, Log::Any::App > 0.23 will support specifying
        # sub { ... } to refer to general level
        category_level => {Dumps => 'trace'},
    };

for (qw/username password data_dir log_dir/) {
    defined($App::options{$_}) or die "Missing required argument: $_\n";
}

mkpath($App::options{data_dir})                       unless (-d $App::options{data_dir});
die "Can't create data_dir `$App::options{data_dir}'" unless (-d $App::options{data_dir});

$log->info("Start session");

my $ibank = Finance::Bank::ID::BPRKS->new(
    username    => $App::options{username},
    password    => $App::options{password},
    logger      => $log,
    logger_dump => Log::Any->get_logger(category => "Dumps"),
    verify_https => 1,
);

eval {
    my @bal = $ibank->_check_balances;
    $log->debug("Balances: ".$ibank->_dmp(\@bal));

    my $stmt = $ibank->get_statement(
        account => $App::options{account},
        days => $App::options{days},
        parse_opts => {return_datetime_obj=>0},
    );
    my $filename = sprintf "%s/bprks.statement.%s.%s.to.%s.yaml",
        $App::options{data_dir},
        $stmt->{account},
        $stmt->{start_date},
        $stmt->{end_date};
    $filename =~ s/[: ]//g; # : is for windows
    $log->info("Writing statements to YAML file `$filename' ...");

    write_file($filename, Dump($stmt));
};

if ($@) {
    $log->error("die: $@");
}

# no matter what, try to logout so we're not locked out for 10 minutes, annoying
eval { $ibank->logout; };

$log->info("End session");

# ABSTRACT: Download BPR KS statement
# PODNAME: download-bprks

__END__

=pod

=encoding UTF-8

=head1 NAME

download-bprks - Download BPR KS statement

=head1 VERSION

This document describes version 0.02 of download-bprks (from Perl distribution Finance-Bank-ID-BPRKS), released on 2014-05-17.

=head1 SYNOPSIS

First, put your username and password in ~/.app/download-bprks.conf, e.g.:

 [ALL]
 username = ABCDEF0123
 password = 123456

Then:

 $ download-bprks

Get your statements in data dir (defaults to ~/bprks). See logs in your log dir
(defaults to ~/bprks/logs).

=head1 DESCRIPTION

This is a command-line script which you can run from cron or whatever to
conveniently download BPR KS statements. By default, it downloads 30 day's worth
of statements to ~/bprks/. To change this, use --days and --data_dir options.

=head1 SEE ALSO

L<Finance::Bank::ID::BPRKS>

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/Finance-Bank-ID-BPRKS>.

=head1 SOURCE

Source repository is at L<https://github.com/sharyanto/perl-Finance-Bank-ID-BPRKS>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=Finance-Bank-ID-BPRKS>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

Steven Haryanto <stevenharyanto@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Steven Haryanto.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut