From 761bb699d83bbc65966ad11379b4a8a45daf4b31 Mon Sep 17 00:00:00 2001
From: mulhern <amulhern@redhat.com>
Date: Fri, 31 Jan 2025 15:33:53 -0500
Subject: [PATCH] Make stratis-legacy-pool a command of stratisd-tools

Signed-off-by: mulhern <amulhern@redhat.com>
---
 .github/workflows/fedora.yml                  |  6 --
 Cargo.toml                                    |  8 +--
 Makefile                                      | 15 +----
 src/bin/tools/cmds.rs                         | 66 ++++++++++++++++++-
 .../legacy_pool.rs}                           | 59 ++---------------
 src/bin/tools/mod.rs                          |  1 +
 6 files changed, 75 insertions(+), 80 deletions(-)
 rename src/bin/{stratis-legacy-pool.rs => tools/legacy_pool.rs} (60%)

diff --git a/.github/workflows/fedora.yml b/.github/workflows/fedora.yml
index cc9a94688f..f3cb1927ac 100644
--- a/.github/workflows/fedora.yml
+++ b/.github/workflows/fedora.yml
@@ -45,9 +45,6 @@ jobs:
           - task: PROFILEDIR=debug make -f Makefile build
             toolchain: 1.84.0  # CURRENT DEVELOPMENT RUST TOOLCHAIN
             components: cargo
-          - task: PROFILEDIR=debug make -f Makefile build-test-extras
-            toolchain: 1.84.0  # CURRENT DEVELOPMENT RUST TOOLCHAIN
-            components: cargo
           - task: PROFILEDIR=debug make -f Makefile build-min
             toolchain: 1.84.0  # CURRENT DEVELOPMENT RUST TOOLCHAIN
             components: cargo
@@ -72,9 +69,6 @@ jobs:
           - task: make -f Makefile build
             toolchain: 1.84.0  # CURRENT DEVELOPMENT RUST TOOLCHAIN
             components: cargo
-          - task: make -f Makefile build-test-extras
-            toolchain: 1.84.0  # CURRENT DEVELOPMENT RUST TOOLCHAIN
-            components: cargo
           - task: make -f Makefile build-min
             toolchain: 1.84.0  # CURRENT DEVELOPMENT RUST TOOLCHAIN
             components: cargo
diff --git a/Cargo.toml b/Cargo.toml
index 1edd4ef048..f908636149 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -71,10 +71,6 @@ required-features = ["udev_scripts"]
 name = "stratis-utils"
 required-features = ["engine"]
 
-[[bin]]
-name = "stratis-legacy-pool"
-required-features = ["test_extras"]
-
 [dependencies.async-trait]
 version = "0.1.51"
 optional = true
@@ -295,11 +291,11 @@ engine = [
 ]
 default = ["dbus_enabled", "engine"]
 dbus_enabled = ["dep:dbus", "dep:dbus-tree"]
-extras = ["dep:pretty-hex"]
+extras = ["dep:pretty-hex", "test_extras"]
 min = ["dep:termios"]
 systemd_compat = ["dep:bindgen"]
 udev_scripts = ["dep:data-encoding"]
-test_extras = ["engine"]
+test_extras = []
 
 [lints.rust]
 warnings = { level = "deny" }
diff --git a/Makefile b/Makefile
index 425ec7a6cd..046590eb0b 100644
--- a/Makefile
+++ b/Makefile
@@ -51,7 +51,6 @@ MIN_FEATURES = --no-default-features --features engine,min
 NO_IPC_FEATURES = --no-default-features --features engine
 SYSTEMD_FEATURES = --no-default-features --features engine,min,systemd_compat
 EXTRAS_FEATURES =  --no-default-features --features engine,extras,min
-TEST_EXTRAS_FEATURES = --no-default-features --features test_extras
 UDEV_FEATURES = --no-default-features --features udev_scripts
 UTILS_FEATURES = --no-default-features --features engine,systemd_compat
 
@@ -193,12 +192,6 @@ stratisd-tools:
 	cargo ${BUILD} ${RELEASE_FLAG} \
 	--bin=stratisd-tools ${EXTRAS_FEATURES} ${TARGET_ARGS}
 
-## Build the test extras
-build-test-extras:
-	PKG_CONFIG_ALLOW_CROSS=1 \
-	cargo build ${RELEASE_FLAG} \
-	--bin=stratis-legacy-pool ${TEST_EXTRAS_FEATURES} ${TARGET_ARGS}
-
 ## Build the stratis-dumpmetadata program
 ## Build stratis-min for early userspace
 stratis-min:
@@ -421,12 +414,8 @@ clippy-utils:
 clippy-no-ipc:
 	cargo clippy ${CLIPPY_OPTS} ${NO_IPC_FEATURES}
 
-## Run clippy on no-ipc-build
-clippy-test-extras:
-	cargo clippy ${CLIPPY_OPTS} ${TEST_EXTRAS_FEATURES}
-
 ## Run clippy on the current source tree
-clippy: clippy-macros clippy-min clippy-udev-utils clippy-no-ipc clippy-utils clippy-test-extras
+clippy: clippy-macros clippy-min clippy-udev-utils clippy-no-ipc clippy-utils
 	cargo clippy ${CLIPPY_OPTS}
 
 ## Lint Python parts of the source code
@@ -443,7 +432,6 @@ lint:
 	build-all-man
 	build-all-rust
 	build-min
-	build-test-extras
 	build-udev-utils
 	build-stratis-base32-decode
 	build-stratis-str-cmp
@@ -456,7 +444,6 @@ lint:
 	clippy-macros
 	clippy-min
 	clippy-no-ipc
-	clippy-test-extras
 	clippy-udev-utils
 	docs-ci
 	docs-rust
diff --git a/src/bin/tools/cmds.rs b/src/bin/tools/cmds.rs
index 9fe84b43e4..5ca5f99541 100644
--- a/src/bin/tools/cmds.rs
+++ b/src/bin/tools/cmds.rs
@@ -4,9 +4,9 @@
 
 use std::path::PathBuf;
 
-use clap::{Arg, ArgAction, Command};
+use clap::{Arg, ArgAction, ArgGroup, Command};
 
-use crate::tools::{check_metadata, dump_metadata};
+use crate::tools::{check_metadata, dump_metadata, legacy_pool};
 
 use stratisd::stratis::VERSION;
 
@@ -147,10 +147,72 @@ impl<'a> ToolCommand<'a> for StratisPrintMetadata {
     }
 }
 
+struct StratisLegacyPool;
+
+impl StratisLegacyPool {
+    fn cmd() -> Command {
+        Command::new("stratis-legacy-pool")
+            .version(VERSION)
+            .about("A script for facilitating testing; not to be used in production")
+            .arg(Arg::new("pool_name").num_args(1).required(true))
+            .arg(
+                Arg::new("blockdevs")
+                    .action(ArgAction::Append)
+                    .value_parser(clap::value_parser!(PathBuf))
+                    .required(true),
+            )
+            .arg(
+                Arg::new("key_desc")
+                    .long("key-desc")
+                    .num_args(1)
+                    .required(false),
+            )
+            .arg(
+                Arg::new("clevis")
+                    .long("clevis")
+                    .num_args(1)
+                    .required(false)
+                    .value_parser(["nbde", "tang", "tpm2"])
+                    .requires_if("nbde", "tang_args")
+                    .requires_if("tang", "tang_args"),
+            )
+            .arg(
+                Arg::new("tang_url")
+                    .long("tang-url")
+                    .num_args(1)
+                    .required_if_eq("clevis", "nbde")
+                    .required_if_eq("clevis", "tang"),
+            )
+            .arg(Arg::new("thumbprint").long("thumbprint").num_args(1))
+            .arg(Arg::new("trust_url").long("trust-url").num_args(0))
+            .group(
+                ArgGroup::new("tang_args")
+                    .arg("thumbprint")
+                    .arg("trust_url"),
+            )
+    }
+}
+
+impl<'a> ToolCommand<'a> for StratisLegacyPool {
+    fn name(&self) -> &'a str {
+        "stratis-legacy-pool"
+    }
+
+    fn run(&self, command_line_args: Vec<String>) -> Result<(), String> {
+        let matches = StratisLegacyPool::cmd().get_matches_from(command_line_args);
+        legacy_pool::run(&matches).map_err(|err| format!("{err}"))
+    }
+
+    fn show_in_after_help(&self) -> bool {
+        false
+    }
+}
+
 pub fn cmds<'a>() -> Vec<Box<dyn ToolCommand<'a>>> {
     vec![
         Box::new(StratisCheckMetadata),
         Box::new(StratisDumpMetadata),
+        Box::new(StratisLegacyPool),
         Box::new(StratisPrintMetadata),
     ]
 }
diff --git a/src/bin/stratis-legacy-pool.rs b/src/bin/tools/legacy_pool.rs
similarity index 60%
rename from src/bin/stratis-legacy-pool.rs
rename to src/bin/tools/legacy_pool.rs
index fb5dbaeea0..03d2a4961f 100644
--- a/src/bin/stratis-legacy-pool.rs
+++ b/src/bin/tools/legacy_pool.rs
@@ -2,9 +2,9 @@
 // License, v. 2.0. If a copy of the MPL was not distributed with this
 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-use std::{env, path::PathBuf};
+use std::path::PathBuf;
 
-use clap::{Arg, ArgAction, ArgGroup, Command};
+use clap::ArgMatches;
 use serde_json::{json, Map, Value};
 
 use stratisd::{
@@ -15,45 +15,6 @@ use stratisd::{
     stratis::StratisResult,
 };
 
-fn stratis_legacy_pool_args() -> Command {
-    Command::new("stratis-legacy-pool")
-        .arg(Arg::new("pool_name").num_args(1).required(true))
-        .arg(
-            Arg::new("blockdevs")
-                .action(ArgAction::Append)
-                .required(true),
-        )
-        .arg(
-            Arg::new("key_desc")
-                .long("key-desc")
-                .num_args(1)
-                .required(false),
-        )
-        .arg(
-            Arg::new("clevis")
-                .long("clevis")
-                .num_args(1)
-                .required(false)
-                .value_parser(["nbde", "tang", "tpm2"])
-                .requires_if("nbde", "tang_args")
-                .requires_if("tang", "tang_args"),
-        )
-        .arg(
-            Arg::new("tang_url")
-                .long("tang-url")
-                .num_args(1)
-                .required_if_eq("clevis", "nbde")
-                .required_if_eq("clevis", "tang"),
-        )
-        .arg(Arg::new("thumbprint").long("thumbprint").num_args(1))
-        .arg(Arg::new("trust_url").long("trust-url").num_args(0))
-        .group(
-            ArgGroup::new("tang_args")
-                .arg("thumbprint")
-                .arg("trust_url"),
-        )
-}
-
 type ParseReturn = StratisResult<(
     String,
     Vec<PathBuf>,
@@ -61,19 +22,15 @@ type ParseReturn = StratisResult<(
     Option<(String, Value)>,
 )>;
 
-fn parse_args() -> ParseReturn {
-    let args = env::args().collect::<Vec<_>>();
-    let parser = stratis_legacy_pool_args();
-    let matches = parser.get_matches_from(args);
-
+fn parse_args(matches: &ArgMatches) -> ParseReturn {
     let pool_name = matches
         .get_one::<String>("pool_name")
         .expect("required")
         .clone();
     let blockdevs = matches
-        .get_many::<String>("blockdevs")
+        .get_many::<PathBuf>("blockdevs")
         .expect("required")
-        .map(PathBuf::from)
+        .cloned()
         .collect::<Vec<_>>();
     let key_desc = match matches.get_one::<String>("key_desc") {
         Some(kd) => Some(KeyDescription::try_from(kd)?),
@@ -107,10 +64,8 @@ fn parse_args() -> ParseReturn {
     Ok((pool_name, blockdevs, key_desc, clevis_info))
 }
 
-fn main() -> StratisResult<()> {
-    env_logger::init();
-
-    let (name, devices, key_desc, clevis_info) = parse_args()?;
+pub fn run(matches: &ArgMatches) -> StratisResult<()> {
+    let (name, devices, key_desc, clevis_info) = parse_args(matches)?;
     let unowned = ProcessedPathInfos::try_from(
         devices
             .iter()
diff --git a/src/bin/tools/mod.rs b/src/bin/tools/mod.rs
index a7d3a25f57..42fd600ce7 100644
--- a/src/bin/tools/mod.rs
+++ b/src/bin/tools/mod.rs
@@ -5,5 +5,6 @@
 mod check_metadata;
 mod cmds;
 mod dump_metadata;
+mod legacy_pool;
 
 pub use cmds::cmds;