+(* Write an init file. *)
+and write_init_file () =
+ match !init_file with
+ | NoInitFile -> () (* Do nothing if --no-init-file *)
+ | DefaultInitFile ->
+ let home = try Sys.getenv "HOME" with Not_found -> "/" in
+ let filename = home // ".virt-toprc" in
+ _write_init_file filename
+ | InitFile filename ->
+ _write_init_file filename
+
+and _write_init_file filename =
+ try
+ (* Create the new file as filename.new. *)
+ let chan = open_out (filename ^ ".new") in
+
+ let time = Unix.gettimeofday () in
+ let tm = Unix.localtime time in
+ let printable_date_time =
+ sprintf "%04d-%02d-%02d %02d:%02d:%02d"
+ (tm.Unix.tm_year + 1900) (tm.Unix.tm_mon+1) tm.Unix.tm_mday
+ tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec in
+ let username =
+ try
+ let uid = Unix.geteuid () in
+ (Unix.getpwuid uid).Unix.pw_name
+ with
+ Not_found -> "unknown" in
+
+ let fp = fprintf in
+ let nl () = fp chan "\n" in
+ fp chan "# .virt-toprc virt-top configuration file\n";
+ fp chan "# generated on %s by %s\n" printable_date_time username;
+ nl ();
+ fp chan "display %s\n" (cli_of_display !display_mode);
+ fp chan "delay %g\n" (float !delay /. 1000.);
+ fp chan "hist-cpu %d\n" !historical_cpu_delay;
+ if !iterations <> -1 then fp chan "iterations %d\n" !iterations;
+ fp chan "sort %s\n" (cli_of_sort_order !sort_order);
+ (match !uri with
+ | None -> ()
+ | Some uri -> fp chan "connect %s\n" uri
+ );
+ if !batch_mode = true then fp chan "batch true\n";
+ if !secure_mode = true then fp chan "secure true\n";
+ nl ();
+ fp chan "# To send debug and error messages to a file, uncomment next line\n";
+ fp chan "#debug virt-top.out\n";
+ nl ();
+ fp chan "# Enable CSV output to the named file\n";
+ fp chan "#csv virt-top.csv\n";
+ nl ();
+ fp chan "# To protect this file from being overwritten, uncomment next line\n";
+ fp chan "#overwrite-init-file false\n";
+
+ close_out chan;
+
+ (* If the file exists, rename it as filename.old. *)
+ (try Unix.rename filename (filename ^ ".old")
+ with Unix.Unix_error _ -> ());
+
+ (* Rename filename.new to filename. *)
+ Unix.rename (filename ^ ".new") filename;
+
+ print_msg (sprintf "Wrote settings to %s" filename); sleep 2
+ with
+ | Sys_error err -> print_msg "Error: %s"; sleep 2
+ | Unix.Unix_error (err, fn, str) ->
+ print_msg (sprintf "Error: %s %s %s" (Unix.error_message err) fn str);
+ sleep 2
+