abar 0.6.2

An interface for creating dynamic, "blocks"-style status strings
Documentation
use std::env;
use std::io::Write;
use std::net::TcpStream;

use getopts::Options;

/// Prints usage information for the CLI interface, generated by getopts.
fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} FILE [options]", program);
    print!("{}", opts.usage(&brief));
}

/// Parses arguments from the environment and reacts accordingly. Known flags
/// will be handled here, and all other inputs will be forwarded to the
/// currently running bar over TCP.
pub fn process_args() {
    let args: Vec<String> = env::args().collect();

    // If there were no arguments, simply return.
    if args.len() <= 1 {
        return;
    }

    // Otherwise, define a new set of potential arguments,
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optflag("h", "help", "print this help menu");

    // get matches for those arguments,
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            panic!("{}", f.to_string())
        },
    };

    // and respond to known flags.
    if matches.opt_present("h") {
        print_usage(&program, opts);
        std::process::exit(0);
    }

    // Finally, if the program is still executing, forward any args to the
    // currently running bar (if it exists).
    if let Ok(mut stream) = TcpStream::connect("127.0.0.1:2227") {
        let data = args[1..].join(" ");
        stream.write_all(data.as_bytes()).unwrap();
        std::process::exit(0);
    }
    else {
        eprintln!("Could not connect to a running bar instance.");
        std::process::exit(1);
    }
}