#!/usr/bin/perl

my $RCS_Id = '$Id: ebshell.pl,v 1.9 2006/01/22 16:50:41 jv Exp $ ';

# Author          : Johan Vromans
# Created On      : Thu Jul  7 15:53:48 2005
# Last Modified By: Johan Vromans
# Last Modified On: Sun Jan 22 15:19:09 2006
# Update Count    : 247
# Status          : Unknown, Use with caution!

################ Common stuff ################

use strict;

# Package or program libraries, if appropriate.
# $LIBDIR = $ENV{'LIBDIR'} || '/usr/local/lib/sample';
# use lib qw($LIBDIR);
# require 'common.pl';

# Package name.
my $my_package; BEGIN { $my_package = 'EekBoek' }

# Program name and version.
my ($my_name, $my_version) = $RCS_Id =~ /: (.+).pl,v ([\d.]+)/;
# Tack '*' if it is not checked in into RCS.
$my_version .= '*' if length('$Locker:  $ ') > 12;

################ Configuration ################

our $cfg;

# This will set up the config at 'use' time.
use EB::Config $my_package;

################ Command line parameters ################

use Getopt::Long 2.13;

# Command line options.
my $interactive = -t;
my $command;
my $echo;
my $dataset;
my $createdb;			# create database
my $schema;			# initialise w/ schema
my $confirm = 0;
my $journal = 0;
my $verbose = 0;		# verbose processing
my $bky;

# Development options (not shown with -help).
my $debug = 0;			# debugging
my $trace = 0;			# trace (show process)
my $test = 0;			# test mode.

# Process command line options.
app_options();

# Post-processing.
$trace |= ($debug || $test);

################ Presets ################

my $TMPDIR = $ENV{TMPDIR} || $ENV{TEMP} || '/usr/tmp';

################ The Process ################

use EB;
use base qw(EB::Shell);

my $app = $my_package;
my $userdir = glob("~/.".lc($app));
mkdir($userdir) unless -d $userdir;

$echo = "eb> " if $echo;

$dataset ||= $cfg->val(qw(database name));

unless ( $dataset ) {
    die("?"._T("Geen dataset opgegeven.".
	       " Specificeer een dataset in de configuratiefile,".
	       " of geef een dataset".
	       " naam mee op de command line met \"--dataset=...\".").
	"\n");
}

$cfg->newval(qw(database name), $dataset);

if ( $createdb ) {
    $dataset =~ s/^(?!=eekboek_)/eekboek_/;
    my $cmd;
    my @cmd;

    my @ds = DBI->data_sources("Pg");
    if ( grep { lc($_) =~ /=\Q$dataset\E$/ } @ds ) {
	$cmd = "psql";
	@cmd = ( $cmd, "-X",
		 "-f", EB_LIB . "EB/schema/cleanup.sql" );
    }
    else {
	$cmd = "createdb";
	@cmd = ( $cmd, qw(-E latin1) );
	for ( $cfg->val("database", "user") ) {
	    next unless $_;
	    push(@cmd, "-O", $_);
	}
    }

    for ( $cfg->val("database", "user") ) {
	next unless $_;
	push(@cmd, "-U", $_);
    }
    for ( $cfg->val("database", "password") ) {
	next unless $_;
	push(@cmd, "--password");
    }
    for ( $cfg->val("database", "host") ) {
	next unless $_;
	push(@cmd, "-h", $_);
    }
    for ( $cfg->val("database", "port") ) {
	next unless $_;
	push(@cmd, "-p", $_);
    }
    push(@cmd, $dataset);
    warn("+ @cmd\n") if $trace;
    my $res = system { $cmd } @cmd;
    # warn(sprintf("=> ret = %02x", $res)."\n") if $res;
    die("?"._T("Aanmaken database mislukt")."\n") if $res;
}

use EB::DB;
our $dbh = EB::DB->new(trace => $trace);

if ( $schema ) {
    require EB::Tools::Schema;
    $dbh->connectdb(1);
    EB::Tools::Schema->create($schema);
}

my $shell = EB::Shell->new
  ({ HISTFILE	  => $userdir."/history",
     command	  => $command,
     interactive  => $interactive,
     verbose	  => $verbose,
     trace	  => $trace,
     journal	  => $journal,
     echo	  => $echo,
     prompt	  => lc($app),
     boekjaar	  => $bky,
   });

$| = 1;

$shell->run;

################ Subroutines ################

sub app_options {
    my $help = 0;		# handled locally
    my $ident = 0;		# handled locally

    # Process options, if any.
    # Make sure defaults are set before returning!
    return unless @ARGV > 0;

    if ( !GetOptions(
		     'command|c' => sub {
			 $command = 1;
			 die("!FINISH\n");
		     },
		     'createdb' => \$createdb,
		     'schema=s' => \$schema,
		     'echo!'	=> \$echo,
		     'ident'	=> \$ident,
		     'journaal|journal'	=> \$journal,
		     'boekjaar=s'	=> \$bky,
		     'verbose'	=> \$verbose,
		     'db|dataset=s' => \$dataset,
		     'trace'	=> \$trace,
		     'help|?'	=> \$help,
		     'debug'	=> \$debug,
		    ) or $help )
    {
	app_usage(2);
    }
    app_usage(2) if @ARGV && !$command;
    app_ident() if $ident;
}

sub app_ident {
    print STDERR (__x("Dit is {pkg} [{name} {version}]",
		      pkg     => $my_package,
		      name    => $my_name,
		      version => $my_version) . "\n");
}

sub app_usage {
    my ($exit) = @_;
    app_ident();
    print STDERR __x(<<EndOfUsage, prog => $0);
Gebruik: {prog} [options] [file ...]

    --command  -c       voer de rest van de opdrachtregel uit als command
    --echo  -e          toon ingelezen opdrachten
    --journaal          toon de journaalregels na elke opdracht
    --dataset=DB        specificeer database
    --db=DB             specificeer database
    --boekjaar=XXX	specificeer boekjaar
    --createdb		maak nieuwe database aan
    --schema=XXX        initialisser database met schema
    --help		deze hulpboodschap
    --ident		toon identificatie
    --verbose		geef meer uitgebreide information
EndOfUsage
    exit $exit if defined $exit && $exit != 0;
}

=head1 NAME

ebshell - EekBoek * Bookkeeping shell

=head1 SYNOPSIS

EekBoek is a bookkeeping package for small and medium-size businesses.
Unlike other accounting software, EekBoek has both a command-line
interface (CLI) and a graphical user-interface (GUI). Furthermore, it
has a complete Perl API to create your own custom applications.

EekBoek is designed for the Dutch/European market and currently
available in Dutch only. An English translation is in the works (help
appreciated).

=head1 DESCRIPTION

For a description how to use the program, see L<http://www.squirrel.nl/eekboek/docs/index.html>.

=head1 BUGS AND PROBLEMS

Please use the eekboek-users mailing list at SourceForge.

=head1 AUTHOR AND CREDITS

Johan Vromans (jvromans@squirrel.nl) wrote this module.

Web site: L<http://www.squirrel.nl/eekboek>.

=head1 COPYRIGHT AND DISCLAIMER

This program is Copyright 2005,2006 by Squirrel Consultancy. All
rights reserved.

This program is free software; you can redistribute it and/or modify
it under the terms of either: a) the GNU General Public License as
published by the Free Software Foundation; either version 1, or (at
your option) any later version, or b) the "Artistic License" which
comes with Perl.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the
GNU General Public License or the Artistic License for more details.

=cut
