oxidepath 0.1.0-alpha.1

An experimental Rust proxy core targeting mihomo configuration compatibility
mod config;
mod hosts;
mod proxy;

use std::{
    env,
    error::Error,
    ffi::OsString,
    fs,
    io::{self, Read},
    path::PathBuf,
    process::ExitCode,
};

use config::Config;

const USAGE: &str = "Usage: oxidepath [-t] [-d directory] [-f file|-]\n\
                     -t  Check the configuration and exit\n\
                     -d  Set the default configuration directory\n\
                     -f  Read a YAML file or use - for standard input\n\
                     -v  Print the version";

#[derive(Default)]
struct Options {
    directory: Option<PathBuf>,
    file: Option<PathBuf>,
    check: bool,
}

fn next_path(arguments: &mut impl Iterator<Item = OsString>, flag: &str) -> io::Result<PathBuf> {
    arguments
        .next()
        .map(PathBuf::from)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{flag} needs a path")))
}

fn default_directory() -> PathBuf {
    if let Some(config_home) = env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty()) {
        return PathBuf::from(config_home).join("oxidepath");
    }
    env::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".config")
        .join("oxidepath")
}

fn read_configuration(options: &Options) -> io::Result<String> {
    let directory = options
        .directory
        .clone()
        .or_else(|| {
            env::var_os("CLASH_HOME_DIR")
                .filter(|value| !value.is_empty())
                .map(PathBuf::from)
        })
        .unwrap_or_else(default_directory);
    let path = options
        .file
        .clone()
        .or_else(|| {
            env::var_os("CLASH_CONFIG_FILE")
                .filter(|value| !value.is_empty())
                .map(PathBuf::from)
        })
        .unwrap_or_else(|| directory.join("config.yaml"));
    if path.as_os_str() == "-" {
        let mut input = String::new();
        io::stdin().read_to_string(&mut input)?;
        return Ok(input);
    }
    fs::read_to_string(&path)
        .map_err(|error| io::Error::new(error.kind(), format!("{}: {error}", path.display())))
}

fn run() -> Result<(), Box<dyn Error>> {
    let mut options = Options::default();
    let mut arguments = env::args_os().skip(1);
    while let Some(argument) = arguments.next() {
        match argument.to_str() {
            Some("-h" | "--help") => {
                println!("{USAGE}");
                return Ok(());
            }
            Some("-v" | "--version") => {
                println!("oxidepath {}", env!("CARGO_PKG_VERSION"));
                return Ok(());
            }
            Some("-t") => options.check = true,
            Some("-d") => options.directory = Some(next_path(&mut arguments, "-d")?),
            Some("-f") => options.file = Some(next_path(&mut arguments, "-f")?),
            _ => return Err(format!("Unknown argument {argument:?}\n{USAGE}").into()),
        }
    }

    let config = Config::parse(&read_configuration(&options)?)?;
    if options.check {
        println!("configuration test is successful");
        return Ok(());
    }
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?
        .block_on(proxy::run(config))?;
    Ok(())
}

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("oxidepath: {error}");
            ExitCode::FAILURE
        }
    }
}