use arboard::Clipboard;
use itertools::Itertools;
use rspw::Arguments;
use std::{
env::{self, args, args_os},
ffi::OsString,
process, thread, time,
};
const DAEMONIZE: &str = "__rspw_daemon";
const SLEEP_TIME: u64 = 30;
fn main() {
let input = check_rspw_daemon();
if input.clipboard {
spawn_rspw_daemon();
} else {
let password = input.generate_passwd().unwrap_or_else(|err| {
println!("Password cant be generated: {}", err);
process::exit(1);
});
if args().nth(args_os().len() - 1).as_deref() == Some(DAEMONIZE) {
let _ = rspw_clipboard(password);
} else {
println!("{}", password);
}
}
}
fn check_rspw_daemon() -> Arguments {
if args().nth(args_os().len() - 1).as_deref() == Some(DAEMONIZE) {
Arguments::init_daemon(args_os().dropping_back(1))
} else {
Arguments::init()
}
}
fn rspw_clipboard(password: String) -> Result<(), ()> {
let mut clipboard = Clipboard::new().unwrap_or_else(|err| {
println!("Could not create a clipboard instance: {}", err.to_string());
process::exit(1);
});
clipboard.set_text(password).unwrap_or_else(|err| {
println!("Could not set text to the clipboard: {}", err.to_string());
process::exit(1);
});
thread::sleep(time::Duration::from_secs(SLEEP_TIME));
clipboard.clear().unwrap_or_else(|err| {
println!("Could not clear the clipboard: {}", err.to_string());
process::exit(1);
});
Ok(())
}
fn spawn_rspw_daemon() {
println!(
"Password will be copied on the clipboard, clears in {} seconds.",
SLEEP_TIME
);
if cfg!(target_os = "linux") {
process::Command::new(env::current_exe().unwrap_or_else(|err| {
println!("Could not find current path: {}", err.to_string());
process::exit(1);
}))
.args(filtered_args())
.arg(DAEMONIZE)
.stdin(process::Stdio::null())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null())
.current_dir("/")
.spawn()
.unwrap_or_else(|err| {
println!("Could not spawn child process: {}", err.to_string());
println!("Cannot add password to the clipboard!");
process::exit(1);
});
}
}
fn filtered_args() -> impl Iterator<Item = OsString> {
let mut filt_vec: Vec<OsString> = args_os().filter(|x| x != "-c").collect();
let _ = filt_vec.remove(0);
filt_vec.into_iter()
}