delegate run_if_script properly
[scpubgit/App-SCS.git] / lib / App / SCS.pm
1 package App::SCS;
2
3 use Module::Runtime qw(use_module);
4 use IO::All;
5 use Moo;
6
7 with 'App::SCS::Role::WithConfig';
8
9 has plugins => (is => 'ro', default => sub { [] });
10
11 has root_dir => (is => 'lazy');
12
13 sub _build_root_dir {
14   my ($self) = @_;
15   io->dir(io->dir($self->config->{root_dir})->absolute);
16 }
17
18 has share_dir => (is => 'lazy');
19
20 sub _build_share_dir {
21   my ($self) = @_;
22   io->dir($self->config->{share_dir}||$self->root_dir->catdir('share'));
23 }
24
25 has page_plugin_config => (is => 'lazy');
26
27 sub _build_page_plugin_config {
28   my ($self) = @_;
29   return {
30     plugin_map => {
31       do {
32         my %map = map $_->page_plugins, reverse @{$self->plugins};
33         ref($_) or $_ = { class => $_, config => sub {} } for values %map;
34         %map;
35       }
36     },
37     defaults => [
38       map $_->default_page_plugins, @{$self->plugins}
39     ],
40   };
41 }
42
43 has pages => (is => 'lazy');
44
45 sub _build_pages {
46   my ($self) = @_;
47   return use_module('App::SCS::PageSet')->new(
48     base_dir => $self->share_dir->catdir('pages'),
49     plugin_config => $self->page_plugin_config,
50   );
51 }
52
53 has web => (is => 'lazy');
54
55 sub _build_web {
56   my ($self) = @_;
57   return use_module('App::SCS::Web')->new(
58     app => $self
59   );
60 }
61
62 sub BUILD {
63   my ($self) = @_;
64   $self->load_plugin(Core => {});
65   my @plist = @{$self->config->{plugins}||[]};
66   while (my ($name, $conf) = splice @plist, 0, 2) {
67     $self->load_plugin($name, $conf);
68   }
69 }
70
71 sub load_plugin {
72   my ($self, $name, $config) = @_;
73   my $class = ($name =~ s/^\+// ? $name : "App::SCS::Plugin::${name}");
74   push(
75     @{$self->plugins},
76     use_module($class)->new(
77       app => $self,
78       config => $config
79     )
80   );
81   return;
82 }
83
84 sub run_if_script {
85   my $self = shift;
86   if (caller(1)) {
87     return $self->web->to_psgi_app;
88   } else {
89     return $self->run;
90   }
91 }
92
93 sub run {
94   my $self = shift;
95   my $env = {
96     argv => \@ARGV,
97     stdin => \*STDIN,
98     stdout => \*STDOUT,
99     stderr => \*STDERR,
100   };
101   foreach my $p (@{$self->plugins}) {
102     return if $p->run_cli($env);
103   }
104   $self->web->run;
105 }
106
107 1;