#!/usr/bin/env perl
#----------------------------------------
use strict;
use warnings qw(FATAL all NONFATAL misc);
use constant DEBUG_LIB => $ENV{DEBUG_YATT_CLI_LIB};
use FindBin; BEGIN {
  if (-r (my $libFn = "$FindBin::RealBin/libdir.pl")) {
    print STDERR "# using $libFn\n" if DEBUG_LIB;
    do $libFn
  }
  elsif ($FindBin::RealBin =~ m{/local/bin$ }x) {
    print STDERR "# using local/lib/perl5\n" if DEBUG_LIB;
    require lib;
    lib->import($FindBin::RealBin . "/../lib/perl5");
  }
  else {
    print STDERR "# No special libdir\n" if DEBUG_LIB;
  }
}
sub MY () {__PACKAGE__}
#----------------------------------------

use YATT::Lite::Entities qw/*SYS/;
use YATT::Lite::Factory;
use YATT::Lite::Breakpoint;
use YATT::Lite::Util qw(rootname);
use YATT::Lite::Util::CmdLine;

use YATT::Lite::CGen::Perl; # Just for debugging aid.
# XXX: 各ディレクトリに .htyattcf.xhf が有ったら? rc が有ったら?
# XXX: それらが無い状態で、 Web::* 環境での動作検証をしたいときは?

use YATT::Lite::Types
  ([Opts => -fields => [qw/cf_all/]]);

my Opts $opts = Opts->new(MY->parse_opts(\@ARGV));

local $SYS = my $dispatcher = YATT::Lite::Factory->load_factory_offline
  || do {
  require YATT::Lite::WebMVC0::SiteApp;
  YATT::Lite::WebMVC0::SiteApp->new
      (app_ns => 'MyYATT'
       , namespace => ['yatt', 'perl', 'js']
       , header_charset => 'utf-8'
       , debug_cgen => $ENV{DEBUG}
       , debug_cgi  => $ENV{DEBUG_CGI}
       # , is_gateway => $ENV{GATEWAY_INTERFACE} # Too early for FastCGI.
       # , tmpl_encoding => 'utf-8'
      );
};

my $nerror = 0;
foreach my $fn (@ARGV) {
  my $dir = File::Basename::dirname($dispatcher->rel2abs($fn));
  my $dirhandler = $dispatcher->get_dirhandler($dir);
  $dirhandler->fconfigure_encoding(\*STDOUT, \*STDERR);
  my $trans = $dirhandler->open_trans;
  my $tmpl = $trans->find_file(File::Basename::basename($fn)) or do {
    warn "No such file: $fn\n";
    $nerror++;
    next;
  };
  # XXX: encoding
  my $pkg = $trans->find_product(perl => $tmpl, sink => sub {
					my ($info, @script) = @_;
					if (not $opts->{cf_all}) {
					  return unless $info->{'depth'} == 1;
				        }
					print @script;
				      });
}

exit 1 if $nerror;