open Common_options
open Type_options
(*open Md4*)

type action = Get of string | Set | User of string 

let _ = 
  let action = ref None
  in
  let filename = ref None
  in
  let password = ref ""
  in
  let _ = Arg.parse [
    ("-f", Arg.String (fun x -> filename := Some x), "Open options file");
    ("-g", Arg.String (fun x -> action := Some (Get x)), "Get options in the file");
    ("-s", Arg.Unit (fun x -> action := Some Set), "Set options in the file")(*;
    ("-u", Arg.String(fun x -> action := Some (User x)), "Edit user password")*)
    ]
    (fun x -> password := x )
    "Usage : mldonkey_options [options]\n where options are:"
  in
  begin
  match !filename, !action with
  | None, _ ->
    print_string "You must provide the name of the file to open -f";
    print_newline ();
    exit 1
  | Some(f), Some(Get(o)) ->
    begin
    try
      let v = find_option o (load_option f)
      in
      print_simple_value v;
      print_newline ()
    with Not_found ->
      prerr_string ("Unable to find option "^o);
      prerr_newline ();
      exit 1
    end
(*  | Some(f), Some(User(u)) ->
    let options = load_option f
    in
    let v = find_option "users" options
    in
    let is_user x =
        match x with
        ValList(lst) ->
          begin
          try 
            (List.hd lst) != (ValIdent u)
          with _ ->
            false
          end
        | _ ->
          false
    in
    let old_user_list =
      match v with
      ValList(lst) ->
        List.filter is_user lst 
      | _ ->
        []
    in
    let new_password = 
      Md4.to_string (Md4.string !password)
    in
    let new_user_list =
      ValList([ValIdent(u); ValString(new_password)]) :: old_user_list
    in
    let new_option =
       Id ("users", ValList(new_user_list))
    in
    save_option f (replace_option new_option options)*)
  | Some(f), Some(Set) 
  | Some(f), _ ->
    let new_options = parse_option ()
    in
    let options = load_option f
    in
    let rec set_one_option set_fl fl =
      match set_fl with
      | Comment(_, f) ->
        set_one_option f fl 
      | Options(o, f) ->
        set_one_option f (replace_option o fl)
      | Eof ->
        fl
    in
    save_option f (set_one_option new_options options)
  end
