(*
 *    _  _   ____                         _  
 *  _| || |_/ ___|  ___ _ __  _ __   ___ | | 
 * |_  ..  _\___ \ / _ \ '_ \| '_ \ / _ \| | 
 * |_      _|___) |  __/ |_) | |_) | (_) |_| 
 *   |_||_| |____/ \___| .__/| .__/ \___/(_) 
 *                     |_|   |_|             
 *
 * Personal Social Web.
 *
 * Copyright (C) The #Seppo contributors. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *)


module C = Cgi
open Seppo_lib

let () =
  Mirage_crypto_rng_lwt.initialize (module Mirage_crypto_rng.Fortuna);
  (let uuid = Uuidm.v `V4 in
   let resp_err ec ?(hdrs = [Http.H.ct_plain]) status msg =
     Cgi.Response.flush uuid stdout (status, hdrs, fun oc ->
         let s = status |> Cohttp.Code.string_of_status in
         Printf.eprintf "FATAL: %s\r\nsee %s\r\n%s\r\n" s ec msg;
         Printf.fprintf oc "Status: %s\r\n\r\n%s\r\n%s" s ec msg ) in
   try match Cgi.Request.from_env () |> Cgi.Request.consolidate with
     | Error "Not Found." ->
       (* some CLI commands are fine without logging. At least -h and -V have to. *)
       Sys.argv
       |> Array.to_list
       |> Shell.exec
     | Error msg -> resp_err E.e1036 `Internal_server_error msg
     | Ok req ->
       (
         (* try to write logfile into app/var/log/ from the current directory **)
         let bin_dir = 0 |> Array.get Sys.argv |> Filename.dirname in
         assert (bin_dir |> St.ends_with ~suffix:"/" |> not);
       ); (* allow to execute from anywhere
             assert (bin_dir |> String.equal (Unix.getcwd ())); *)
       match "app/var/log/" |> File.mkdir_p 0o770 with
       | Error msg -> resp_err E.e1035 `Internal_server_error msg
       | Ok log_dir ->
         let tnow = Ptime_clock.now () in
         assert (log_dir |> St.ends_with ~suffix:"/");
         Logr.open_out (log_dir ^ "seppo.log"); 
         let r = req
                 |> C.handle uuid tnow stdin
                 |> Cgi.Response.flush uuid stdout in
         close_in stdin;
         (* closing kills the cgi: close_out stdout; *)
         flush stderr;
         (* L.close_out (); *)
         r
   with
   | Sys_error msg -> resp_err E.e1034 `Internal_server_error msg
   | e -> resp_err E.e1005 `Internal_server_error (Printexc.to_string e) )
  |> exit
