let download ~base_url ~output_file = let output_file = Fpath.v output_file in let base_url = Uri.of_string base_url in let uri = Uri.with_path base_url "/management/keys/" in let uri = Uri.to_string uri in Miou_unix.run @@ fun () -> let rng = Mirage_crypto_rng_miou_unix.(initialize (module Pfortuna)) in let finally () = Mirage_crypto_rng_miou_unix.kill rng in Fun.protect ~finally @@ fun () -> let fn _meta _req _resp buf = function | Some str -> Buffer.add_string buf str; buf | None -> buf in let prm = Miou.async @@ fun () -> Httpcats.request ~fn ~uri (Buffer.create 0x1000) in match Miou.await prm with | Error _exn -> Fmt.failwith "Download failure: exn@." | Ok (Error err) -> Fmt.failwith "Download failure: `%a`@." Httpcats.pp_error err | Ok (Ok (_resp, buf)) -> ( let data = Buffer.to_bytes buf |> Bytes.to_string in match Bos.OS.File.write output_file data with | Error (`Msg err) -> Fmt.failwith "Download write failure: `%s`@." err | Ok () -> ()) (* CLI *) open Cmdliner open Cmdliner.Term.Syntax let output = let doc = "File to save data to be signed." in Arg.( value & opt filepath "management_keys.json" & info [ "o"; "output" ] ~doc) let base_url = let doc = "Base url of the exchange." in Arg.(value & opt string "http://localhost:3434/" & info [ "base-url" ] ~doc) let download_cmd = let doc = "Downloads /management/keys/" in let man = [ `S Manpage.s_description; `P "$(cmd) download /management/keys." ] in Cmd.make (Cmd.info "offline" ~version:"%%VERSION%%" ~doc ~man) @@ let+ output_file = output and+ base_url = base_url in download ~base_url ~output_file let main () = try Cmd.eval download_cmd with Failure err -> Fmt.epr "%s@." err; exit 1 let () = if !Sys.interactive then () else exit (main ())