#!/usr/bin/perl

use Art5;

my $dump = 0;
my $v;
my $s;
my @path = ();
my $cache = undef;
my $profile = 0;

# raw argument parsing
while ($v = shift(@ARGV)) {
    if ($v eq '-d') {
        $dump  = 1;
    }
    elsif ($v eq '-I') {
        push(@path, shift(@ARGV));
    }
    elsif ($v eq '-c') {
        $cache = shift(@ARGV);
    }
    elsif ($v eq '-l') {
        update_lang();
    }
    elsif ($v eq '-h') {
        usage();
    }
    elsif ($v eq '-p') {
        $profile = 1;
    }
    else {
        # script name
    }
}

if (!defined($s)) {
    $s = join('', <>);
}

my $a = Art5->new( path => \@path, cache => $cache, profile => $profile);

my $c = $a->compile($s);

if ($dump) {
    use Data::Dumper;

    print Dumper($c), "\n";
}
else {
    print $a->exec($c);
}

if ($a->{profile}) {
    print("Timed calls:\n");
    print(join("\n", @{$a->{timed_calls}}), "\n");
}

exit 0;



sub update_lang
# updates all language files
{
    my @lang = glob("lang_*");

    if (scalar(@lang) == 0) {
        print "Error: no lang_* files.\n";
        exit 1;
    }

    # read now all templates in the current directory
    # searching for translateable strings
    my %h = ();

    foreach my $t (glob("*")) {
        # skip language files themselves
        if ($t =~ /lang_.*$/) {
            next;
        }

        # read template
        if (open F, $t) {
            my $l;

            while ($l = <F>) {
                my @s = ($l =~ /@\"([^\"]+)"/g);

                foreach my $s (@s) {
                    $h{$s}++;
                }
            }

            close F;
        }
    }

    my $a = Art5->new( path => ['.']);

    # now all keys in the templates must be
    # merged into each language file
    # ...

    foreach my $l (@lang) {
        print "Rebulding $l...\n";

        # load and execute this template file
        my $c = $a->code($l);
        $a->exec($c);

        open F, ">$l";

        print F "<{T\n";
        foreach my $k (sort keys(%h)) {
            print F "\"$k\" \n";
            print F "\"", ($a->{t}->{$k} || ''), "\"\n\n";
        }
        print F "}>\n";

        close F;
    }

    exit 0;
}


sub usage {
    print <<EOF;

Artemus 5 Command Line Interpreter
Copyright (C) 2000/2014 Angel Ortega <angel\@triptico.com>

Usage:

art5 [options]

Options
-------

 -d       Do not execute the compiled code, but dump it (using
          Data::Dumper).
 -I {dir} Add {dir} to the template search path.
 -c {dir} Use {dir} as a folder to store caching information.
 -l       Reads all templates in the current directory, extracts all
          translateable strings and updates all templates matching
          'lang_*' with them. To start with a new language, just
          create an empty language file.
 -p       Dump profiling information after executing the program.
 -h       Show this help.

EOF

    exit 0;
}
