Read and decode key file
[rup.git] / src / main.rs
index 7a179af..c5a7dc1 100644 (file)
@@ -7,9 +7,12 @@ use actix_files as fs;
 use actix_web::{web, middleware, App, HttpServer, HttpResponse, Responder, Result, web::Query};
 use askama::Template;
 
+use std::io::prelude::*;
 use ron::de::from_reader;
 use serde::Deserialize;
-use std::fs::File;
+use std::{fs::File, env::args};
+
+use itertools::Itertools;
 
 mod consts;
 mod crypto;
@@ -50,8 +53,54 @@ struct Config {
     port: u16
 }
 
+fn get_exe_name() -> String {
+    let first_arg = std::env::args().nth(0).unwrap();
+    //dbg!(&first_arg);
+    let sep: &[_] = &['\\', '/'];
+    first_arg[first_arg.rfind(sep).unwrap()+1..].to_string()
+}
+
+fn print_usage() {
+    println!("Usage:");
+    println!(" {} [--help] [--encrypt <message>]", get_exe_name());
+}
+
+fn read_key() -> String {
+    use url::percent_encoding::percent_decode;
+    let mut key = String::new();
+    File::open(consts::FILE_KEY)
+        .expect(&format!("Failed to open key file: {}", consts::FILE_KEY))
+        .read_to_string(&mut key)
+        .expect(&format!("Failed to read key file: {}", consts::FILE_KEY));
+
+    String::from(
+        percent_decode(key.as_bytes())
+            .decode_utf8()
+            .expect(&format!("Failed to decode key file: {}", consts::FILE_KEY))
+    )
+}
+
 fn main() -> std::io::Result<()> {
-    println!("Starting RUP...");
+    let args: Vec<String> = args().collect();
+
+    let key = read_key();
+
+    if args.iter().any(|arg| arg == "--help") {
+        print_usage();
+        return Ok(());
+    } else if let Some((position_arg_encrypt, _)) = args.iter().find_position(|arg| arg == &"--encrypt") {
+        match args.iter().nth(position_arg_encrypt + 1) {
+            Some(mess_to_encrypt) => {
+                let encrypted_mess = crypto::encrypt(&key, mess_to_encrypt);
+                println!("Encrypted message: {}", encrypted_mess);
+            }
+            None => print_usage()
+        }
+
+        return Ok(());
+    }
+
+    println!("Starting RUP as web server...");
 
     let config: Config = {
         let f = File::open(consts::FILE_CONF).expect(&format!("Failed to open configuration file {}", consts::FILE_CONF));