aboutsummaryrefslogtreecommitdiff
path: root/src/guff.cr
blob: f0e26711ddd229faeda1c3329a3f11b39b2bde1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
require "http/server"
require "ecr/macros"
require "json"
require "yaml"
require "secure_random"
require "sqlite3"

module Guff
  VERSION = "0.1.0"
end

require "./guff/**"

private macro include_api_modules(modules)
  {% for mod in modules.resolve %}
    include {{ mod.id }}
  {% end %}
end

private macro api_method_dispatch(modules)
  case namespace
  {% for mod in modules.resolve %}
    {% mod_name = mod.resolve.name.gsub(/^.*:(.*)API$/, "\\1").downcase %}
    when {{ mod_name.stringify }}
    case method
    {% for mod_method in mod.resolve.methods %}
      {% method_name = mod_method.name.gsub(/^do_([^_]+)_/, "") %}
      when {{ method_name.stringify }}
        {{ mod_method.name.id }}(params)
    {% end %}
    else
      raise "unknown method: #{namespace}/#{method}"
    end
  {% end %}
  else
    raise "unknown namespace: #{namespace}"
  end
end

module Guff
  module Views
    abstract class View
      def initialize(@context : Context)
      end

      def h(s : String) : String
        HTML.escape(s)
      end
    end

    class TabView < View
      def initialize(
        context : Context,
        @prefix : String,
        @tab : Hash(Symbol, String)
      )
        super(context)
        @id = h("%s-tab-%s" % [@prefix, @tab[:id]]) as String
        @target = h("%s-pane-%s" % [@prefix, @tab[:id]]) as String
      end

      private def v(id : Symbol) : String
        raise "unknown id: #{id}" unless @tab.has_key?(id)
        h(@tab[id])
      end

      ECR.def_to_s("src/views/tab.ecr")
    end

    module Dropdown
      module Icon
        ICON_TEMPLATE = "<i class='fa fa-fw %s'></i>"

        def self.icon(id : String?)
          if id && id.size > 0
            ICON_TEMPLATE % [HTML.escape(id.not_nil!)]
          else
            ""
          end
        end
      end

      class ItemView < View
        def initialize(
          context  : Context,
          @active  : Bool,
          @item    : Hash(Symbol, String)
        )
          super(context)
        end

        private def v(id : Symbol)
          h(@item[id])
        end

        private def li_css
          @active ? "class='active'" : ""
        end

        ECR.def_to_s("src/views/dropdown/item.ecr")
      end

      class MenuView < View
        def initialize(
          context   : Context,
          @id       : String,
          @name     : String,
          @text     : String,
          @css      : String,
          @icon     : String,
          @default  : String,
          @items    : Array(Hash(Symbol, String))
        )
          super(context)

          @default_name = @items.reduce("") do |r, row|
            (row[:id]? == @default) ? row[:name] : r
          end as String
        end

        private def items
          String.build do |io|
            @items.each do |item|
              io << ItemView.new(
                context:  @context,
                active:   @default == item[:id]?,
                item:     item
              ).to_s
            end
          end
        end

        ECR.def_to_s("src/views/dropdown/menu.ecr")
      end
    end

    abstract class HTMLView < View
      TEMPLATES = {
        script: "<script type='text/javascript' src='%s'></script>",
        style:  "<link rel='stylesheet' type='text/css' href='%s'/>",
      }

      private def assets(key : Symbol, paths : Array(String))
        String.build do |io|
          paths.each do |path|
            io << TEMPLATES[key] % [h(path)]
          end
        end
      end

      def scripts(paths : Array(String))
        assets(:script, paths)
      end

      def styles(paths : Array(String))
        assets(:style, paths)
      end

      def tabs(prefix : String, rows : Array(Hash(Symbol, String)))
        String.build do |io|
          rows.each do |row|
            TabView.new(@context, prefix, row).to_s(io)
          end
        end
      end

      def dropdown(
        id      : String,
        name    : String,
        text    : String,
        icon    : String,
        css     : String,
        default : String,
        items   : Array(Hash(Symbol, String))
      )
        Dropdown::MenuView.new(
          context:  @context,
          id:       id,
          name:     name,
          text:     text,
          icon:     icon,
          css:      css,
          default:  default,
          items:    items
        ).to_s
      end
    end

    class AdminPageView < HTMLView
      TITLE = "Guff Admin"

      TABS = {
        "admin" => [{
          :id   => "home",
          :css  => "active",
          :icon => "fa-home",
          :name => "Home",
          :text => "View home tab.",
        }, {
          :id   => "posts",
          :css  => "",
          :icon => "fa-cubes",
          :name => "Posts",
          :text => "Manage blog, pages, and projects.",
        }, {
          :id   => "files",
          :css  => "",
          :icon => "fa-files-o",
          :name => "Files",
          :text => "Manage files.",
        }, {
          :id   => "settings",
          :css  => "",
          :icon => "fa-cogs",
          :name => "Settings",
          :text => "Configure settings.",
        }],

        "settings" => [{
          :id   => "general",
          :css  => "active",
          :icon => "fa-cog",
          :name => "General",
          :text => "Manage general settings.",
        }, {
          :id   => "backups",
          :css  => "",
          :icon => "fa-archive",
          :name => "Backups",
          :text => "Manage backups.",
        }, {
          :id   => "import",
          :css  => "",
          :icon => "fa-upload",
          :name => "Import / Export",
          :text => "Import and export posts.",
        }, {
          :id   => "sites",
          :css  => "",
          :icon => "fa-sitemap",
          :name => "Sites",
          :text => "Manage sites and domains.",
        }, {
          :id   => "themes",
          :css  => "",
          :icon => "fa-eye",
          :name => "Themes",
          :text => "Manage themes.",
        }, {
          :id   => "users",
          :css  => "",
          :icon => "fa-users",
          :name => "Users",
          :text => "Manage users and permissions.",
        }],
      }

      TEMPLATES = {
        :option => "
          <option value='%s'>%s</option>
        ",

        :new_post_button => "
          <a
            href='#'
            class='btn btn-primary'
            title='Create new blog post, page, or project.'
            data-toggle='dropdown'
          >
            <i class='fa fa-plus-circle'></i>
            Create
            <i class='fa fa-fw fa-caret-down'></i>
          </a>

          <ul class='dropdown-menu'>
            <li>
              <a
                href='#'
                title='Create new blog post.'
                class='add-post'
                data-type='blog'
              >
                <i class='fa fa-fw fa-sticky-note-o'></i>
                Blog Post
              </a>
            </li>

            <li>
              <a
                href='#'
                title='Create new page.'
                class='add-post'
                data-type='page'
              >
                <i class='fa fa-fw fa-bookmark-o'></i>
                Page
              </a>
            </li>

            <li>
              <a
                href='#'
                title='Create new project.'
                class='add-post'
                data-type='project'
              >
                <i class='fa fa-fw fa-cube'></i>
                Project
              </a>
            </li>
          </ul>
        ",

        :state_button => "
          <a
            href='#'
            class='btn btn-default'
            title='Mark as %s.'
            data-val='%s'
          >
            <i class='fa %s'></i>
            %s
          </a>
        ",
      }

      def tabs(id : String)
        super(id, TABS[id])
      end

      private def new_post_button
        TEMPLATES[:new_post_button]
      end

      private def role_options
        @role_options ||= String.build do |io|
          @context.models.role.get_roles.each do |row|
            io << TEMPLATES[:option] % %w{role name}.map { |key| h(row[key]) }
          end
        end
      end

      private def state_buttons
        @state_buttons ||= String.build do |io|
          @context.models.state.get_states.each do |row|
            io << TEMPLATES[:state_button] % [
              h(row["name"]),
              h(row["state"]),
              h(row["icon"]),
              h(row["name"])
            ]
          end
        end
      end

      private def authors_menu_items
        @context.models.user.get_users.map do |row|
          {
            :id   => row["user_id"],
            :name => row["name"],
            :text => "Show author \"%s\"." % [row["name"]],
          }
        end
      end

      private def sites_menu_items
        @context.models.site.get_sites.map do |row|
          {
            :id   => row["site_id"],
            :name => row["name"],
            :text => "Show site \"%s\"." % [row["name"]],
          }
        end
      end

      private def states_menu_items
        @context.models.state.get_states.map do |row|
          {
            :id   => row["state"],
            :name => row["name"],
            :icon => row["icon"],
            :text => "Show state \"%s\"." % [row["name"]],
          }
        end
      end

      ECR.def_to_s("src/views/admin-page.ecr")
    end

    class LoginPageView < HTMLView
      def initialize(context : Context, @error : String? = nil)
        super(context)
      end

      def get_csrf_token
        @context.models.csrf.create_token
      end

      ECR.def_to_s("src/views/login-page.ecr")
    end

    class LogoutPageView < HTMLView
      ECR.def_to_s("src/views/logout-page.ecr")
    end

    class BlogListItemView < HTMLView
      def initialize(context : Context, @post_id : Int64)
        super(context)
      end

      ECR.def_to_s("src/views/blog/list-item.ecr")
    end

    #
    # TODO: add y/m/d/page
    #
    class BlogListView < HTMLView
      TITLE = "Blog List"

      def initialize(context : Context, @post_ids : Array(Int64))
        super(context)
      end

      def posts
        String.build do |io|
          @post_ids.each do |id|
            BlogListItemView.new(@context, id).to_s(io)
          end
        end
      end

      ECR.def_to_s("src/views/blog/list.ecr")
    end
  end

  module Handlers
    abstract class Handler < HTTP::Handler
      def initialize(@context : Context)
        super()
      end

      protected def valid_origin_headers?(headers : HTTP::Headers)
        # FIXME: need to compare these against something rather than
        # just making sure that they are there
        %w{origin referer}.any? do |key|
          headers[key]? && headers[key].size > 0
        end
      end

      protected def get_site_id(host : String?) : Int64?
        @context.models.site.get_id(host)
      end
    end

    abstract class AuthenticatedHandler < Handler
      def initialize(context : Context, @roles : Array(String))
        super(context)
      end

      def call(context : HTTP::Server::Context)
        if @context.has_role?(@roles)
          authenticated_call(context)
        else
          call_next(context)
        end
      end

      abstract def authenticated_call(context : HTTP::Server::Context)
    end

    class StubHandler < Handler
      def call(context : HTTP::Server::Context)
        STDERR.puts "%s %s" % [
          context.request.method,
          context.request.path.not_nil!
        ]

        call_next(context)
      end
    end

    class SessionHandler < Handler
      def call(context : HTTP::Server::Context)
        # clear session
        @context.session.clear

        if cookie = context.request.cookies[Guff::Session::COOKIE]?
          # load session
          @context.session.load(cookie.value)
        end

        call_next(context)

        if @context.session.valid?
          @context.session.save
        end
      end
    end

    class APIHandler < Handler
      PATH_RE = %r{^/guff/api/(?<namespace>[\w_-]+)/(?<method>[\w_-]+)$}

      API_MODULES = [
        APIs::PostAPI,
        APIs::UserAPI,
        APIs::PageAPI,
        APIs::ProjectAPI,
        APIs::BlogAPI,
        APIs::SiteAPI,
      ]

      include_api_modules(API_MODULES)

      def call(context : HTTP::Server::Context)
        if context.request.method == "POST" ||
           (@context.development? && context.request.method == "GET")
          if md = PATH_RE.match(context.request.path.not_nil!)
            namespace, method = %w{namespace method}.map { |k| md[k] }

            # get query parameteres
            params = if (context.request.method == "GET")
              context.request.query_params
            else
              HTTP::Params.parse(context.request.body || "")
            end

            code, data = begin
              { 200, api_method_dispatch(API_MODULES) }
            rescue err
              STDERR.puts "ERROR: #{err}"
              { 400, { "error": err.to_s } }
            end

            # send json response
            context.response.status_code = code
            context.response.content_type = "application/json; charset=utf-8"
            data.to_json(context.response)
          else
            call_next(context)
          end
        else
          call_next(context)
        end
      end
    end

    class AssetsHandler < Handler
      def initialize(context : Context)
        super(context)
        @etags = {} of String => String
      end

      def call(context : HTTP::Server::Context)
        req_path = context.request.path.not_nil!

        if matching_request?(context.request.method, req_path) &&
           valid_origin_headers?(context.request.headers)
          # get expanded path to file
          if abs_path = expand_path(req_path)
            # get file digest
            etag = get_file_etag(abs_path)

            # check for cache header
            if context.request.headers["if-none-match"]? == etag
              # cached, send 304 not modified
              context.response.status_code = 304
            else
              # not cached, set code and send headers
              context.response.headers["x-frame-options"] = "SAMEORIGIN"
              context.response.status_code = 200
              context.response.content_type = AssetMimeType.from_path(abs_path)
              context.response.content_length = File.size(abs_path)
              context.response.headers["etag"] = etag

              if context.request.method == "GET"
                # send body for GET requests
                File.open(abs_path) do |fh|
                  STDERR.puts "sending #{abs_path}"
                  IO.copy(fh, context.response)
                  STDERR.puts "done sending #{abs_path}"
                end
              end
            end
          else
            # expanded path does not exist
            call_next(context)
          end
        else
          # not a matching request
          call_next(context)
        end
      end

      VALID_METHODS = %w{GET HEAD}
      PATH_RE = %r{^/guff/assets/}

      private def matching_request?(method, path)
        VALID_METHODS.includes?(method) && PATH_RE.match(path)
      end

      private def expand_path(req_path : String) : String?
        # unescape path, check for nil byte
        path = URI.unescape(req_path)
        return nil if path.includes?('\0')

        # build absolute path
        r = File.join(
          @context.config.system_dir,
          "assets",
          File.expand_path(path.gsub(PATH_RE, ""), "/")
        )

        # return path if file exists, or nil otherwise
        File.file?(r) ? r : nil
      end

      private def get_file_etag(path : String) : String
        # FIXME: rather than a hash this should be an HMAC
        @etags[path] ||= OpenSSL::Digest.new("SHA1").file(path).hexdigest
      end
    end

    class AdminPageHandler < AuthenticatedHandler
      def initialize(context : Context)
        super(context, %w{admin editor})
      end

      PATH_RE = %r{^/guff/admin\.html$}

      def authenticated_call(context : HTTP::Server::Context)
        if context.request.path.not_nil!.match(PATH_RE)
          context.response.headers["x-frame-options"] = "SAMEORIGIN"
          context.response.content_type = "text/html; charset=utf-8"
          context.response.status_code = 200
          Views::AdminPageView.new(@context).to_s(context.response)
        else
          call_next(context)
        end
      end
    end

    class LoginPageHandler < Handler
      PATH_RE = %r{^/guff/login\.html$}
      VALID_METHODS = %w{GET POST}

      def call(context : HTTP::Server::Context)
        if VALID_METHODS.includes?(context.request.method) &&
           PATH_RE.match(context.request.path.not_nil!)
          case context.request.method
          when "GET"
            reply(context.response)
          when "POST"
            begin
              # check for valid origin or referer header
              unless valid_origin_headers?(context.request.headers)
                raise "missing origin and referer headers"
              end

              # create session
              session_id = @context.session.create({
                "user_id" => login(context.request.body).to_s,
              })

              # add cookie
              context.response.cookies << HTTP::Cookie.new(
                name:       Guff::Session::COOKIE,
                value:      session_id as String,
                http_only:  true,

                # TODO
                # expires:
                # secure:
              )

              # redirect to admin panel
              context.response.headers["location"] = "/guff/admin.html"
              context.response.status_code = 302
            rescue err
              # log error
              STDERR.puts "login failed: #{err}"
              reply(context.response, "invalid login")
            end
          else
            raise "invalid HTTP method"
          end
        else
          call_next(context)
        end
      end

      private def reply(
        response : HTTP::Server::Response,
        error : String? = nil
      )
        response.headers["x-frame-options"] = "SAMEORIGIN"
        response.content_type = "text/html; charset=utf-8"
        response.status_code = 200
        Views::LoginPageView.new(@context, error).to_s(response)
      end

      private def login(body : String?)
        # check body
        raise "empty request body" if body.nil? || body.size == 0

        # parse request parameters
        params = HTTP::Params.parse(body.not_nil!)

        # check login parameters
        raise "missing login parameters" unless %w{
          username
          password
          csrf_token
        }.all? do |key|
          params.has_key?(key) && params[key].size > 0
        end

        # check csrf token
        unless @context.models.csrf.use_token(params["csrf_token"])
          raise "invalid csrf token"
        end

        # try login
        user_id =  @context.models.user.login(
          params["username"],
          params["password"]
        )

        # check user id
        raise "invalid credentials" unless user_id

        # return user id
        user_id.not_nil!
      end
    end

    class LogoutPageHandler < Handler
      PATH_RE = %r{^/guff/logout\.html$}

      def call(context : HTTP::Server::Context)
        if context.request.method == "GET" &&
           PATH_RE.match(context.request.path.not_nil!) &&
           valid_origin_headers?(context.request.headers)
          # delete session
          @context.session.delete

          # clear cookie
          context.response.cookies << HTTP::Cookie.new(
            name:       Guff::Session::COOKIE,
            value:      "",
            expires:    Time.epoch(0),
            http_only:  true,
          )

          # build remaining headers
          context.response.headers["x-frame-options"] = "SAMEORIGIN"
          context.response.content_type = "text/html; charset=utf-8"
          context.response.status_code = 200

          # draw page
          Views::LogoutPageView.new(@context).to_s(context.response)
        else
          call_next(context)
        end
      end
    end

    class PageHandler < Handler
      PATH_RE = %r{^/(?<slug>[^/]+)\.html$}

      def call(context : HTTP::Server::Context)
        if post_id = get_post_id(context.request)
          # TODO: render page
          context.response.headers["x-frame-options"] = "SAMEORIGIN"
          context.response.content_type = "text/html; charset=utf-8"
          context.response.status_code = 200
          context.response << "page: #{post_id}"
        else
          # unknown page
          call_next(context)
        end
      end

      private def get_post_id(request : HTTP::Request) : Int64?
        r = nil

        if request.method == "GET"
          if md = PATH_RE.match(request.path.not_nil!)
            if site_id = get_site_id(request.headers["host"]?)
              r = @context.models.page.get_id(
                site_id: site_id,
                slug: md["slug"],
              )
            end
          end
        end

        # return result
        r
      end
    end

    class ProjectHandler < Handler
      PATH_RE = %r{^/(?<slug>[^/]+)/?$}

      def call(context : HTTP::Server::Context)
        if post_id = get_post_id(context.request)
          path = context.request.path.not_nil!

          if /\/$/.match(path)
            # TODO: render page
            context.response.headers["x-frame-options"] = "SAMEORIGIN"
            context.response.content_type = "text/html; charset=utf-8"
            context.response.status_code = 200
            context.response << "project: #{post_id}"
          else
            # redirect to project
            context.response.headers["location"] = path + "/"
            context.response.status_code = 302
          end
        else
          # unknown page
          call_next(context)
        end
      end

      private def get_post_id(request : HTTP::Request) : Int64?
        r = nil

        if request.method == "GET"
          if md = PATH_RE.match(request.path.not_nil!)
            if site_id = get_site_id(request.headers["host"]?)
              r = @context.models.project.get_id(
                site_id: site_id,
                slug: md["slug"],
              )
            end
          end
        end

        # return result
        r
      end
    end

    class BlogPostHandler < Handler
      PATH_RE = %r{^
        (/blog)?
        /(?<year>\d{4})
        /(?<month>\d{2})
        /(?<day>\d{2})
        /(?<slug>[^/]+)\.html
      $}x

      def call(context : HTTP::Server::Context)
        if id = get_id(context.request)
          # TODO: render page
          context.response.headers["x-frame-options"] = "SAMEORIGIN"
          context.response.content_type = "text/html; charset=utf-8"
          context.response.status_code = 200
          context.response << "blog post id: #{id}"
        else
          # unknown page
          call_next(context)
        end
      end

      private def get_id(request : HTTP::Request) : Int64?
        r = nil

        if request.method == "GET"
          if md = PATH_RE.match(request.path.not_nil!)
            if site_id = get_site_id(request.headers["host"]?)
              r = @context.models.blog.get_id(
                site_id:  site_id,
                year:     md["year"].to_i,
                month:    md["month"].to_i,
                day:      md["day"].to_i,
                slug:     md["slug"],
              )
            end
          end
        end

        # return result
        r
      end
    end

    class BlogListHandler < Handler
      # TODO: make index page configurable
      PATH_RE = %r{^/
        (blog/?)?
        (
          (?<year>\d{4})/
          (
            (?<month>\d{2})/
            ((?<day>\d{2})/)?
          )?
        )?
      $}x

      def call(context : HTTP::Server::Context)
        if ids = get_ids(context.request)
          # TODO: render page
          context.response.headers["x-frame-options"] = "SAMEORIGIN"
          context.response.content_type = "text/html; charset=utf-8"
          context.response.status_code = 200

          Views::BlogListView.new(@context, ids).to_s(context.response)
        else
          # unknown page
          call_next(context)
        end
      end

      private def get_ids(request : HTTP::Request) : Array(Int64)?
        r = nil

        if request.method == "GET"
          if md = PATH_RE.match(request.path.not_nil!)
            if site_id = get_site_id(request.headers["host"]?)
              # get request parameters
              params = request.query_params

              r = @context.models.blog.get_ids(
                site_id:  site_id,
                year:     md["year"]? ? md["year"].to_i : nil,
                month:    md["month"]? ? md["month"].to_i : nil,
                day:      md["day"]? ? md["day"].to_i : nil,
                page:     params["page"]? ? params["page"].to_i : nil,
              )
            end
          end
        end

        # return result
        r
      end
    end

    HANDLERS = [{
      :dev  => true,
      :id   => :stub,
    }, {
      :dev  => true,
      :id   => :error,
    }, {
      :dev  => false,
      :id   => :log,
    }, {
      :dev  => false,
      :id   => :deflate,
    }, {
      :dev  => false,
      :id   => :assets,
    }, {
      :dev  => false,
      :id   => :page,
    }, {
      :dev  => false,
      :id   => :project,
    }, {
      :dev  => false,
      :id   => :blog_post,
    }, {
      :dev  => false,
      :id   => :blog_list,
    }, {
      :dev  => false,
      :id   => :login,
    }, {
      :dev  => false,
      :id   => :session,
    }, {
      :dev  => false,
      :id   => :api,
    }, {
      :dev  => false,
      :id   => :admin,
    }, {
      :dev  => false,
      :id   => :logout,
    }]

    def self.get(context : Context) : Array(HTTP::Handler)
      HANDLERS.select { |row|
        !(row[:dev] as Bool) || context.development?
      }.map { |row|
        make_handler(row[:id] as Symbol, context)
      }
    end

    def self.make_handler(
      handler_id : Symbol,
      context : Context
    ) : HTTP::Handler
      case handler_id
      when :stub
        StubHandler.new(context)
      when :error
        HTTP::ErrorHandler.new
      when :log
        HTTP::LogHandler.new
      when :deflate
        HTTP::DeflateHandler.new
      when :session
        SessionHandler.new(context)
      when :api
        APIHandler.new(context)
      when :assets
        AssetsHandler.new(context)
      when :admin
        AdminPageHandler.new(context)
      when :login
        LoginPageHandler.new(context)
      when :logout
        LogoutPageHandler.new(context)
      when :page
        PageHandler.new(context)
      when :blog_post
        BlogPostHandler.new(context)
      when :blog_list
        BlogListHandler.new(context)
      when :project
        ProjectHandler.new(context)
      else
        raise "unknown handler id: #{handler_id}"
      end
    end
  end

  module CLI
    module Actions
      abstract class Action
        def self.run(config : Config)
          new(config).run
        end

        def initialize(@config : Config)
        end

        abstract def run
      end

      class InitAction < Action
        class Data
          YAML.mapping({
            init_sql:   Array(String),
            add_user:   String,
            test_posts: Array(String),
          })

          def self.load(system_dir : String) : Data
            self.from_yaml(File.read(File.join(system_dir, "init.yaml")))
          end
        end

        def initialize(config : Config)
          super(config)

          # read init data
          @data = Data.load(@config.system_dir)
        end

        def run
          STDERR.puts "Initializing data directory"
          Dir.mkdir(@config.data_dir) unless Dir.exists?(@config.data_dir)

          Guff::Database.new(@config.db_path) do |db|
            @data.init_sql.each do |sql|
              db.query(sql)
            end

            # gen random password and add admin user
            # TODO: move these to init.yaml
            password = Password.random_password
            add_user(db, "Admin", "admin@admin", password)
            add_user(db, "Test", "test@test", "test")
            add_test_posts(db)

            STDERR.puts "admin user: admin@admin, password: #{password}"
          end
        end

        private def add_user(
          db        : Database,
          name      : String,
          email     : String,
          password  : String
        ) : Int64
          db.query(@data.add_user, [
            name,
            email,
            Password.create(password),
            "admin",
          ])
          db.last_insert_row_id.to_i64
        end

        private def add_test_posts(db)
          # STDERR.puts "DEBUG: adding test data"
          @data.test_posts.each do |sql|
            db.query(sql)
          end
        end
      end

      class RunAction < Action
        def run
          STDERR.puts "Running web server"
          check_dirs

          # create context
          context = Context.new(@config)

          STDERR.puts "listening on %s:%s" % [@config.host, @config.port]

          # run server
          HTTP::Server.new(
            @config.host,
            @config.port.to_i,
            Handlers.get(context)
          ).listen
        end

        private def check_dirs
          {
            system: @config.system_dir,
            data:   @config.data_dir,
          }.each do |name, dir|
            unless Dir.exists?(dir)
              raise "missing #{name} directory: \"#{dir}\""
            end
          end
        end
      end
    end

    def self.run(app : String, args : Array(String))
      begin
        begin
          # parse command-line arguments
          config = Config.parse(app, args)
        rescue err
          raise "#{err}.  Use --help for usage"
        end

        case config.mode
        when "init"
          Actions::InitAction.run(config)
        when "run"
          Actions::RunAction.run(config)
        when "help"
          # do nothing
        else
          # never reached
          raise "unknown mode: #{config.mode}"
        end
      rescue err
        STDERR.puts "ERROR: #{err}."
        exit -1
      end
    end
  end
end

Guff::CLI.run($0, ARGV)