cli: Extract basic CLI init into cli_common

Move the first initialization steps (log callback setting,
version/banner printing, and libflashprog init) into a new
function cli_init(). This will be shared by other CLIs.

Change-Id: I9f19006aac18ffcdc05159957d58a2668c41e2b1
Signed-off-by: Nico Huber <nico.h@gmx.de>
Reviewed-on: https://review.sourcearcade.org/c/flashprog/+/72987
diff --git a/cli_classic.c b/cli_classic.c
index 711db5b..2f16ef6 100644
--- a/cli_classic.c
+++ b/cli_classic.c
@@ -97,16 +97,6 @@
 	}
 }
 
-/* Ensure a file is open by means of fstat */
-static bool check_file(FILE *file)
-{
-	struct stat statbuf;
-
-	if (fstat(fileno(file), &statbuf) < 0)
-		return false;
-	return true;
-}
-
 static int do_read(struct flashctx *const flash, const char *const filename)
 {
 	int ret;
@@ -252,22 +242,7 @@
 	struct layout_args layout_args = { 0 };
 	struct layout_include_args *include_args = NULL;
 
-	/*
-	 * Safety-guard against a user who has (mistakenly) closed
-	 * stdout or stderr before exec'ing flashprog.  We disable
-	 * logging in this case to prevent writing log data to a flash
-	 * chip when a flash device gets opened with fd 1 or 2.
-	 */
-	if (check_file(stdout) && check_file(stderr)) {
-		flashprog_set_log_callback(
-			(flashprog_log_callback *)&flashprog_print_cb);
-	}
-
-	print_version();
-	print_banner();
-
-	/* FIXME: Delay calibration should happen in programmer code. */
-	if (flashprog_init(1))
+	if (cli_init())
 		exit(1);
 
 	setbuf(stdout, NULL);
diff --git a/cli_common.c b/cli_common.c
index 787e47d..024881c 100644
--- a/cli_common.c
+++ b/cli_common.c
@@ -16,6 +16,7 @@
  * GNU General Public License for more details.
  */
 
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
@@ -35,6 +36,34 @@
 	return 0;
 }
 
+/* Ensure a file is open by means of fstat */
+static bool cli_check_file(FILE *file)
+{
+	struct stat statbuf;
+
+	if (fstat(fileno(file), &statbuf) < 0)
+		return false;
+	return true;
+}
+
+int cli_init(void)
+{
+	/*
+	 * Safety-guard against a user who has (mistakenly) closed
+	 * stdout or stderr before exec'ing flashprog.  We disable
+	 * logging in this case to prevent writing log data to a flash
+	 * chip when a flash device gets opened with fd 1 or 2.
+	 */
+	if (cli_check_file(stdout) && cli_check_file(stderr)) {
+		flashprog_set_log_callback((flashprog_log_callback *)&flashprog_print_cb);
+	}
+
+	print_version();
+	print_banner();
+
+	return flashprog_init(/* perform_selfcheck => */1);
+}
+
 int cli_parse_log_args(struct log_args *const args, const int opt, const char *const optarg)
 {
 	switch (opt) {
diff --git a/include/cli.h b/include/cli.h
index aec1a46..b7a0340 100644
--- a/include/cli.h
+++ b/include/cli.h
@@ -60,4 +60,6 @@
 int cli_parse_layout_args(struct layout_args *, int opt, const char *optarg);
 int cli_process_layout_args(struct flashprog_layout **, struct flashprog_flashctx *, const struct layout_args *);
 
+int cli_init(void);
+
 #endif