use std::{
    io,
    net::SocketAddr,
    path::{Path, PathBuf},
    process::ExitStatus,
};
use tokio::process::Command;

const MILTERTEST_PROGRAM: &str = "/usr/bin/miltertest";

pub async fn run_miltertest(
    file_name: impl AsRef<Path>,
    addr: SocketAddr,
) -> io::Result<ExitStatus> {
    let file_name = test_path(file_name);
    let port = addr.port();

    // stdout and stderr are not captured with `spawn`. Instead any such output
    // will be printed directly to the console by default.

    let mut miltertest = Command::new(MILTERTEST_PROGRAM)
        // .arg("-vvv")  // verbose miltertest output
        .arg("-D")
        .arg(format!("port={port}"))
        .arg("-s")
        .arg(&file_name)
        .spawn()?;

    miltertest.wait().await
}

fn test_path(file_name: impl AsRef<Path>) -> PathBuf {
    Path::new("tests").join(file_name)
}
