(**************************************************************************)
(*  Copyright © 2009 Stéphane Glondu <steph@glondu.net>                   *)
(*                                                                        *)
(*  This program is free software: you can redistribute it and/or modify  *)
(*  it under the terms of the GNU Affero General Public License as        *)
(*  published by the Free Software Foundation, either version 3 of the    *)
(*  License, or (at your option) any later version, with the additional   *)
(*  exemption that compiling, linking, and/or using OpenSSL is allowed.   *)
(*                                                                        *)
(*  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     *)
(*  Affero General Public License for more details.                       *)
(*                                                                        *)
(*  You should have received a copy of the GNU Affero General Public      *)
(*  License along with this program.  If not, see                         *)
(*  <http://www.gnu.org/licenses/>.                                       *)
(**************************************************************************)

open Printf
open Ben
open Modules
module Marshal = Marshal.Make (Marshallable)
open Marshallable

let args = ref []
let anon_fun name = args := name :: !args
let sources_re = Re.Pcre.regexp "[sS]ources.*"

let is_source x =
  try
    ignore (Re.Pcre.exec ~rex:sources_re x);
    true
  with Not_found -> false

let is_cache x = String.ends_with x ~suffix:".cache"

let usage cmd =
  fprintf stderr "Usage: %s <query> [ file ... ]\n" cmd;
  exit 1

let filters = ref []

let spec =
  Arg.align
    [
      ( "-s",
        Arg.String (fun s -> filters := String.split_on_char ',' s),
        " Show only the body of these fields from the matching paragraphs" );
    ]

let main () =
  let query, files =
    match List.rev !args with
    | query :: files -> (query, files)
    | _ -> usage (sprintf "%s query" Sys.argv.(0))
  in
  let query = Query.of_string query in
  let caches, files = List.partition is_cache files in
  let sources, packages = List.partition is_source files in
  let sources = caches @ sources and packages = caches @ packages in
  let print (type a) (kind : a Package.kind) filename =
    let keep _ = true in
    let eval e _ p =
      if e p query then Package.filter_print !filters Format.std_formatter p
    in
    let accu n p () = eval (Query.eval kind) n p in
    match filename with
    | "-" ->
        Utils.parse_control_in_channel kind "standard input" stdin keep accu ()
    | filename when Compression.file_is_compressed filename ->
        let tool =
          Compression.display_tool
            (Compression.of_string (FilePath.get_extension filename))
        in
        let ic = Unix.open_process_in (Printf.sprintf "%s %s" tool filename) in
        Core.with_in_channel ic (fun ic ->
            Utils.parse_control_in_channel kind filename ic keep accu ())
    | filename when is_cache filename -> (
        let { src_map = srcs; bin_map = bins } = Marshal.load filename in
        match kind with
        | Binary -> PAMap.iter (eval Query.eval_binary) bins
        | Source -> Package.Map.iter (eval Query.eval_source) srcs)
    | filename -> Utils.parse_control_file kind filename keep accu ()
  in
  List.iter (print Source) sources;
  List.iter (print Binary) packages;
  Format.pp_print_flush Format.std_formatter ()

let frontend =
  {
    Frontend.name = "query";
    Frontend.main;
    Frontend.anon_fun;
    Frontend.help = spec;
  }
