basic porting work for SCSite
[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   push(
74     @{$self->plugins},
75     use_module("App::SCS::Plugin::${name}")->new(
76       app => $self,
77       config => $config
78     )
79   );
80   return;
81 }
82
83 sub run_if_script {
84   my $self = shift;
85   if (caller(1)) {
86     return 1;
87   } else {
88     return $self->run;
89   }
90 }
91
92 sub run {
93   my $self = shift;
94   my $env = {
95     argv => \@ARGV,
96     stdin => \*STDIN,
97     stdout => \*STDOUT,
98     stderr => \*STDERR,
99   };
100   foreach my $p (@{$self->plugins}) {
101     return if $p->run_cli($env);
102   }
103   $self->web->run;
104 }
105
106 1;