#[macro_use]
extern crate serde_derive;
extern crate actix_web;
extern crate crypto;
extern crate docopt;
extern crate env_logger;
extern crate reqwest;
extern crate serde_json;
#[macro_use]
extern crate log;

extern crate rookeries;

use crypto::pbkdf2::pbkdf2_simple;
use docopt::Docopt;
use rookeries::web::run_server;

const USAGE: &'static str = "

Usage:
    rookeries (-h | --help)
    rookeries --version
    rookeries run <port>
    rookeries password <pass>

Options:
    -h --help       Show this help screen
    --version       Show version

Subcommands:
    run <port>      Start as web server on the specified port
";

#[derive(Debug, Deserialize)]
struct Args {
    flag_version: bool,
    arg_port: u32,
    arg_pass: String,
}

fn main() {
    env_logger::init();

    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.deserialize())
        .unwrap_or_else(|e| e.exit());

    if args.flag_version {
        println!("{}", get_app_version());
        std::process::exit(0);
    }

    if args.arg_pass != "" {
        println!("{}", pbkdf2_simple(&args.arg_pass, 5000).unwrap());
        std::process::exit(0);
    }

    if args.arg_port > 0 {
        let app = run_server(args.arg_port);
        if app.is_err() {
            error!(
                "Could not start server on port {} because {}",
                args.arg_port,
                app.unwrap_err()
            );
            info!("Exiting...");
            std::process::exit(1);
        }
    }
}

fn get_app_version() -> String {
    format!(
        "rookeries v{version} (c) 2018 {authors}",
        version = env!("CARGO_PKG_VERSION"),
        authors = env!("CARGO_PKG_AUTHORS"),
    ).to_string()
}
