(* Copyright © 2026 Stéphane Glondu. Licensed under GPL-2+. *)

open Support

let ocaml_stdlib_dir =
  lazy
    (match pread "ocamlc -where" with
    | None -> exit 2
    | Some x -> String.trim x)

let config =
  lazy
    ("debian/dh-ocaml.conf.json" |> loadFile
    |> Option.map Yojson.Safe.from_string)

let split_lines str =
  let n = String.length str in
  let rec loop accu i =
    if i < n then
      let j =
        match String.index_from_opt str i '\n' with None -> n | Some j -> j
      in
      loop (String.sub str i (j - i) :: accu) (j + 1)
    else List.rev accu
  in
  loop [] 0

let split_lines_opt = function None -> [] | Some x -> split_lines x

let merge_lines lines =
  let b = Buffer.create 4096 in
  List.iter
    (fun x ->
      Buffer.add_string b x;
      Buffer.add_char b '\n')
    lines;
  Buffer.contents b

let extract ~prefix ~suffix x =
  if String.starts_with ~prefix x then
    let nprefix = String.length prefix in
    let n = String.length x in
    if String.ends_with ~suffix x then
      let nsuffix = String.length suffix in
      Some (String.sub x nprefix (n - nprefix - nsuffix))
    else None
  else None

module SMap = Map.Make (String)

let mem_remove what xs =
  let rec loop accu = function
    | [] -> None
    | x :: xs ->
        if x = what then Some (List.rev_append accu xs) else loop (x :: accu) xs
  in
  loop [] xs
