use std::collections::HashMap;
use std::env;
use std::fs;
use std::fs::read_to_string;
use std::io::stdin;
use std::io::Write;
use std::path::PathBuf;
use std::process;
use std::str::FromStr;
use std::thread;
use std::time::Duration;
use clearscreen::clear;
use directories::UserDirs;
use clearscreen;

#[derive(Clone)]
struct Project{
    customer: String,
    project_name: String,
    notes_folder: PathBuf,
    files_folder: PathBuf,
    active: bool,
    boxname: String,
    id: i32,
} 



fn install(config_path: &PathBuf){
    let mut _terminal_commands = HashMap::from([
        ("konsole", "konsole -e !!!"),
        ("gnome", "gnome-terminal -- bash !!!"),
        ("xfce", "xfce4-terminal --execute '!!!'"),
        ("alacritty", "alacritty -e !!!"),
    ]);
    let mut config_folder_path: PathBuf = config_path.clone();
    config_folder_path.pop();
    let mut projects_conf_path = config_folder_path.clone();
    let del_on_fail = config_folder_path.clone();
    projects_conf_path.push("projects.conf");
    fs::create_dir_all(config_folder_path).expect("error creating config dir");
    let mut config_file = fs::File::create(config_path).expect("error creating file");
    let mut projects_conf_file = fs::File::create(projects_conf_path).expect("error creating projects config file");
    projects_conf_file.write_all(b"customer:name:notes:files:active:box_name\n").expect("error writing default project info");
    let mut terminal_response = String::new();
    let mut notes_response = String::new();
    let mut files_response = String::new();
    let mut tools_response = String::new();
    let mut template_name = String::new();
    let mut have_template = String::new();
    println!("terminal you use? (example: konsole, xfce, gnome, etc)");
    std::io::stdin().read_line(&mut terminal_response).unwrap();
    let mut _terminal_command = String::new();
    if terminal_response.contains("konsole"){
        let mut response_buffer = String::new();
        println!("do you already have a custom profile setup?");
        println!("this is pretty specific to pyro's setup, I do some special sauce for my konsole stuff");
        std::io::stdin().read_line(&mut response_buffer).unwrap();
        if response_buffer.to_lowercase().contains("y"){
            let mut profile = String::new();
            println!("konsole profile name?");
            std::io::stdin().read_line(&mut profile).unwrap();
            _terminal_command = format!("konsole --profile {}", profile);
        }
    }
    else{
        _terminal_command = _terminal_commands[terminal_response.trim_end()].to_owned();
    }
    println!("path to save project notes?");
    std::io::stdin().read_line(&mut notes_response).unwrap();
    println!("path to save project files?");
    std::io::stdin().read_line(&mut files_response).unwrap();
    println!("path to folder with your custom tools?");
    std::io::stdin().read_line(&mut tools_response).unwrap();
    print!("
This tool is mainly to handle distrobox creation and usage.
It's expecting you to have a distrobox that you will use as a template.
Do you have a distrobox set up to function as your template for all new projects?
");
    std::io::stdin().read_line(&mut have_template).unwrap();
    if have_template.contains("n"){
        println!("please set up a distrobox with root as a template and re-run this tool");
        println!("example distrobox setup command:");
        println!("distrobox create --root --image archlinux --name template");
        println!("then enter that distrobox and install all the tools you want and do what ever setup you need");
        println!("and re-run this tool.");
        process::Command::new("rm").arg(del_on_fail).spawn().expect("ERROR deleting config folder, please manually clean up");
        std::process::exit(1);
    }
    let _list = process::Command::new("distrobox").arg("list").arg("--root").status();
    println!("distrobox template name?");
    std::io::stdin().read_line(&mut template_name).unwrap();
    let config_string = format!("Project_files:{}\nProject_notes:{}\ntools_folder:{}\nterminal:{}", files_response.trim_end(), notes_response.trim_end(), tools_response.trim_end(), _terminal_command.trim_end());
    config_file.write_all(config_string.as_bytes()).expect("error writing to config file");
    let default_projectline = format!("default:default:{}:{}:yes:{}", &notes_response.trim_end(), &files_response.trim_end(), &template_name.trim_end());
    projects_conf_file.write_all(default_projectline.as_bytes()).expect("error writing default project line");
    println!("config file generated and saved to {}\n", config_path.display());
    println!("please make sure to install distrobox:\nhttps://github.com/89luca89/distrobox\n\nthis will require either docker or podman as well.\n\n");
    println!("please rerun the program");
    std::process::exit(1);
}


fn get_projects(config_path: &PathBuf) -> Vec<Project>{
    let mut mut_config_path = config_path.clone();
    mut_config_path.pop();
    mut_config_path.push("projects.conf");
    let mut projects = Vec::new();
    let projects_string = fs::read_to_string(mut_config_path).expect("error reading projects file");
    let project_lines:Vec<&str> = projects_string.split("\n").collect();
    let mut first = 0;
    let mut already_active = false;
    for line in project_lines{
        first = first + 1;
        if first != 1{
            if line.len() > 1{
                let settings: Vec<&str> = line.split(":").collect();
                let customer = settings[0].to_owned();
                let project = settings[1].to_owned();
                let notes_string = settings[2].to_owned();
                let folder_string = settings[3].to_owned();
                let notes_folder = PathBuf::from_str(&notes_string.trim_end()).expect("error reading notes string");
                let project_folder = PathBuf::from_str(&folder_string.trim_end()).expect("error reading folding sering");
                let mut active = false;
                let boxname = settings[5].to_owned();
                if settings[4] == "yes"{
                    if already_active == false{
                        env::set_var("CURRENT_PROJECT_BOX", boxname.clone());
                        already_active = true;
                        active = true;
                    }
                }
                let new_project = Project{customer: customer, project_name: project, files_folder: project_folder, notes_folder: notes_folder, active: active, id: first, boxname: boxname};
                println!("{} {} LOADED!", &new_project.customer, &new_project.project_name);
                projects.push(new_project);
            }
        }
    }
    return projects
}


fn switch_project(projects: &mut Vec<Project>){
    for project in projects.clone(){
        if project.active == false{
            println!("{} {}|{}", project.id, project.customer, project.project_name);
        }
    }
    println!("\nnew project selection?\n");
    let mut response = String::new();
    std::io::stdin().read_line(&mut response).unwrap();
    if response.len() > 1{
        let new_id:i32 = response.trim_end().parse().expect("error converting to i32");
        for project in projects{
            if project.id ==  new_id{
                project.active = true;
                println!("project found switching to {} {}", project.customer, project.project_name);
                env::set_var("CURRENT_PROJECT_BOX", project.boxname.clone());
            }
            else if project.id != new_id{
                project.active = false;
            }
            else{
                println!("error unknown project id")
            }
        }
    }
    else{
        println!("error we need user input here dummy!");
    }
    
}

fn save_projects(projects: &Vec<Project>, config_path: &PathBuf){
   let mut save_file_path = config_path.clone();
   let mut active_set = false;
    save_file_path.pop();
    save_file_path.push("projects.conf");
    let mut save_file = fs::File::create(save_file_path).expect("error creating save_file");
    save_file.write_all(b"customer:name:notes:files:active:time:box_name\n").expect("error writing first line to file");
    for project in projects{
        let default = format!{"{}:{}:{}:{}:", project.customer, project.project_name, project.notes_folder.display(), project.files_folder.display()};
        let mut _outline = String::new();
        if project.active{
            if active_set == false{
                _outline = format!("{}yes:{}\n", default, project.boxname);
                active_set = true;
            }

        }
        else{
            _outline = format!("{}no:{}\n", default, project.boxname);
        }
        save_file.write_all(_outline.as_bytes()).expect("error writing outline");
    }
}


fn get_active_project(projects: &Vec<Project>) -> &Project{
    let mut active_project = &projects[0];
    for project in projects{
        if project.active == true{
            active_project = project
        }
    }
    return active_project
}

fn start_pentest(){
    let mut customer_name = String::new();
    let mut project_name = String::new();
    let mut scope = String::new();
    println!("Customer name?");
    std::io::stdin().read_line(&mut customer_name).unwrap();
    println!("Project name?");
    std::io::stdin().read_line(&mut project_name).unwrap();
    println!("path to scope?");
    std::io::stdin().read_line(&mut scope).unwrap();
    scope.pop();
    project_name.pop();
    customer_name.pop();
    let status = process::Command::new("start_pentest")
                                                .arg(scope)
                                                .arg(customer_name)
                                                .arg(project_name)
                                                .status().expect("error spawning start_pentest");
    if status.success() == false{
        println!("error please cleanup and re-run manually");
    }
}

fn new_project(projects: &mut Vec<Project>, project_dir: &PathBuf, notes_dir: &PathBuf, tools_dir: &PathBuf, boxtemplate: &String, config_path: &PathBuf, new_id: i32){
    let mut new_project_dir = project_dir.clone();
    let mut new_note_dir = notes_dir.clone();
    let mut existing_folders = String::new();
    let mut customer_name = String::new();
    let mut project_name = String::new();
    println!("do you have an existing notes and folder structure to copy over?\ny/n");
    std::io::stdin().read_line(&mut existing_folders).unwrap();
    let mut customer_name = customer_name.trim_end().to_owned();
    let mut project_name = project_name.trim_end().to_owned();
    if existing_folders.contains("y") || existing_folders.contains("Y"){
        println!("NOTE THIS WILL OVERWRITE CUSTOMER NAME AND PROJECT NAME WITH THE 2nd TO LAST AND LAST FOLDER NAMES IN THE PATH YOU'RE COPYING RESPECTIVELY");
        let mut files_to_copy = String::new();
        let mut notes_to_copy = String::new();
        println!("path to project folder folder to copy:");
        std::io::stdin().read_line(&mut files_to_copy).unwrap();
        println!("path to notes folder to copy:");
        std::io::stdin().read_line(&mut notes_to_copy).unwrap();
        //to get rid of the new line chars
        files_to_copy.pop();
        notes_to_copy.pop();
        println!("files to copy: {}", files_to_copy);
        println!("notes to copy: {}", notes_to_copy);
        println!("files destination: {}", new_project_dir.display());
        println!("notes destination: {}", new_note_dir.display()); 
        let folder_move_success = process::Command::new("mv")
                                            .arg("-i")
                                            .arg(&files_to_copy)
                                            .arg(new_project_dir.display().to_string())
                                            .status().expect("unable to call the system mv command");
        let note_move_success = process::Command::new("mv")
                                            .arg("-i")
                                            .arg(&notes_to_copy)
                                            .arg(new_note_dir.display().to_string())
                                            .status().expect("unable to call the system mv command");
        if folder_move_success.success(){
            println!("we copied the project folder correctly!!");
        }
        else{
            println!("failed to copy the project folder, try to move it manually!");
        }
        if note_move_success.success(){
            println!("we copied the notes folder correctly!!");
        }
        else{
            println!("failed to copy the notes folder, try to move it manually!");
        }
        // this lovely set of code takes the folder you gave to copy and tries to find the customername and project name based on directory names
        // this solves a case where the entered customer name or project name does not match the files copied
        let copied_files = PathBuf::from(&files_to_copy);
        customer_name = copied_files.file_name().unwrap().to_str().unwrap().to_owned();
        new_project_dir.push(&customer_name);
        new_note_dir.push(&customer_name);
        match fs::read_dir(&new_project_dir){
            Ok(entries) => {
                for entry in entries{
                    match entry {
                        Ok(entry) => {
                            let entry_path = entry.path();
                            if entry_path.is_dir(){
                                if let Some(dir_name) = entry_path.file_name(){
                                    if let Some(dir_name_str) = dir_name.to_str(){
                                        if dir_name_str.contains("pentest"){
                                            project_name = dir_name_str.to_owned();
                                            println!("pentest folder found! assuming projectname...");
                                            new_project_dir.push(&project_name);
                                            new_note_dir.push(&project_name);
                                        }
                                    }
                                }
                            }
                        }
                        Err(e) => eprintln!("error reading entry name: {}", e)
                    }
                }
            }
            Err(e) => eprintln!("Error reading directory entries: {}", e)
        }
        let mut customer_name_response = String::new();
        let mut project_name_response = String::new();
        println!("Customer_name: {}", &customer_name);
        println!("Is this correct?");
        stdin().read_line(&mut customer_name_response).unwrap();
        println!("Project_name: {}", &project_name);
        println!("Is this corrrect?");
        stdin().read_line(&mut project_name_response).unwrap();
        if customer_name_response.contains(|c: char| c == 'n' || c=='N') || project_name_response.contains(|c: char| c == 'n' || c=='N'){
            println!("oops sorry about that, tried to guess based on the second to last and last folder names");
            if customer_name_response.contains(|c: char| c == 'n' || c =='N'){
                let mut name_response = String::new(); 
                println!("what is the correct customer name?");
                stdin().read_line(&mut name_response).unwrap();
                name_response.pop();
                customer_name = name_response.to_owned();
            }
            if project_name_response.contains(|c: char| c == 'n' || c == 'N'){
                let mut project_response = String::new();
                println!("what is the correct project name?");
                stdin().read_line(&mut project_response).unwrap();
                project_response.pop();
                project_name = project_response.to_owned();
            }
        }
    }
    else{
        println!("customer name?");
        std::io::stdin().read_line(&mut customer_name).unwrap();
        println!("project name?");
        std::io::stdin().read_line(&mut project_name).unwrap();
        // to remove newline characters
        customer_name.pop();
        project_name.pop();
        new_project_dir.push(&customer_name);
        new_note_dir.push(&customer_name);
        new_project_dir.push(&project_name);
        new_note_dir.push(&project_name);
        fs::create_dir_all(&new_project_dir).expect("error creating new files folder");
        fs::create_dir_all(&new_note_dir).expect("error creating new notes folder");
    }
    thread::sleep(Duration::from_secs(2));
    let box_name = format!("atarchbox_{}", customer_name);
    let mut box_name_path = new_project_dir.clone();
    box_name_path.push("boxname");
    let mut box_name_file = fs::File::create(box_name_path).expect("Error creating box name file");
    box_name_file.write_all(&box_name.as_bytes()).expect("error writing boxname to box file");
    let pentest_volume = format!("{}:/pentest:rw", new_project_dir.display());
    let toold_volume = format!("{}:/tools:rw", tools_dir.display());
    println!("distrobox create --root --clone {} --volume {} --volume {} --name {}", boxtemplate, toold_volume,  pentest_volume, box_name);
    let distrobox_result = process::Command::new("distrobox")
                                                                .arg("create")
                                                                .arg("--root")
                                                                .arg("--clone")
                                                                .arg(boxtemplate)
                                                                .arg("--volume")
                                                                .arg(&toold_volume)
                                                                .arg("--volume")
                                                                .arg(&pentest_volume)
                                                                .arg("--name")
                                                                .arg(&box_name)
                                                                .status()
                                                                .expect("error getting distrobox status");
    if distrobox_result.success(){
        println!("we made a distrobox oh boy!");
        let distrobox_start_result = process::Command::new("distrobox")
                                                                        .arg("enter")
                                                                        .arg("--root")
                                                                        .arg(&box_name)
                                                                        .arg("--")
                                                                        .arg("sudo")
                                                                        .arg("-s")
                                                                        .arg("ln")
                                                                        .arg("-sf")
                                                                        .arg("/pentest/boxname")
                                                                        .arg("/etc/boxname")
                                                                        .status()
                                                                        .expect("error getting response from distrobox start");
        if distrobox_start_result.success(){
            println!("distrobox was started as well!!!! good job me!");
        }
        else{
            println!("ooof did not start successfully try entering it yoruself");
            println!("distrobox enter --rrot {} -- sudo -s ln -sf /pentest/boxname /etc/boxname", &box_name);
        }
    }
    else{
        println!("ooof distrobox did not work.... try creating it yourself");
        println!("distrobox create --root --clone {} --volume {} --volume {} --name {}", boxtemplate, &toold_volume, &pentest_volume, &box_name);
        println!("distrobox enter --rrot {} -- sudo -s ln -sf /pentest/boxname /etc/boxname", &box_name);
    }
    let new_project = Project{customer: customer_name.trim_end().to_owned(), 
                                    project_name: project_name.trim_end().to_owned(), 
                                    notes_folder: new_note_dir, 
                                    files_folder:new_project_dir, 
                                    active: false,
                                    id: new_id,
                                    boxname: box_name,
                                      };
    projects.push(new_project);
    save_projects(projects, config_path);

}


fn remove_project(projects: &mut Vec<Project>, config_path: &PathBuf){
    for project in projects.clone(){
        println!("{} {} {}", project.id, project.customer, project.project_name);
    }
    let mut project_to_remove = String::new();
    println!("project to remove?");
    std::io::stdin().read_line(&mut project_to_remove).unwrap();
    if project_to_remove.len() > 1{
        let mut project_to_keep = Vec::new();
        if project_to_remove.len() > 0{
            let remove_id: i32 = project_to_remove.trim_end().parse().unwrap();
            let mut project_set = false;
            for project in projects.clone(){
                if project.id == remove_id{
                    println!("will remove {} {}", project.customer, project.project_name);
                    project_set = true;
                    let _distrobox_stop_status = process::Command::new("distrobox").arg("stop").arg("--root").arg(&project.boxname).status().expect("error stopping distrobox");
                    let distrobox_rm_status = process::Command::new("distrobox-rm")
                                                                            .arg("--root")
                                                                            .arg("-f")
                                                                            .arg(&project.boxname)
                                                                            .status().expect("error calling distrobox");
                    if distrobox_rm_status.success(){
                        println!("Distrobox Removal Successful!!!");
                    }
                    else{
                        println!("Distrobox Removal Failed, manual removal required!");
                    }
                }
                else {
                    println!("{} {} will be kept", project.customer, project.project_name);
                    project_to_keep.push(project);
                }
            }
            if project_set{
                projects.clear();
                projects.append(&mut project_to_keep);
                save_projects(&projects, config_path);
            }
            else{
                println!("error no prjects found to remove")
            }
            
        }
        else{
            println!("we need user in put here dummy!!");
        }
    }
    else{
        println!("we need input here dummy!");
    }
}


fn open_in_dolphin(folder: &str, project: Project){
    let mut to_open = PathBuf::new();
    match folder{
        "notes" => to_open.push(project.notes_folder),
        "files" => to_open.push(project.files_folder),
        _ => println!("unknown entry... this should literally be impossible... how.... how tf did you.... what")
    }
    process::Command::new("dolphin")
                         .arg(to_open)
                         .spawn().expect("error opening dolphin");
}

fn stop_all_boxes(projects: &Vec<Project>){
    let mut problem_childs: Vec<Project> = Vec::new();
    let mut all_done = true;
    for project in projects{
        let stopped = process::Command::new("distrobox")
                             .arg("stop")
                             .arg("--root")
                             .arg(&project.boxname)
                             .status().expect("error spawing distrobox");
        if stopped.success(){
            println!("{} sucessfully stopped!", &project.boxname);
        }
        else{
            println!("{} not stopped!!!!!!!", &project.boxname);
            all_done = false;
            problem_childs.push(project.clone());
        }
    }
    if all_done{
        println!("All boxes stopped GO US YAAAAA WE DID IT");
    }
    else{
        println!("OOOOOOOF some boxes didn't stop yo, that's cringe");
        println!("here are the problem childs, you may need to stop them manually");
        for child in problem_childs{
            println!("{}",child.boxname);
        }
    }
}


fn print_report_information(project: Project){
    let mut general_notes_path = project.notes_folder.clone();
    let mut finding_notes_path = project.notes_folder.clone();
    general_notes_path.push("general.md ");
    finding_notes_path.push("findings.md ");
    println!("general: {}\nfindings: {}", general_notes_path.display(), finding_notes_path.display());
    let  general_string = fs::read_to_string(general_notes_path).expect("error opening general notes");
    let  findings_string = fs::read_to_string(finding_notes_path).expect("error opening findings notes");
    let general_lines: Vec<&str> = general_string.split("\n").collect();
    let finding_lines: Vec<&str> = findings_string.split("\n").collect();
    println!("Scope:");
    for line in general_lines{
        if line.contains("|"){
            let split: Vec<&str> = line.split("|").collect();
            println!("{}\t{}", split[0], split[2]);
        }
    }
    println!("Findings");
    for line in finding_lines{
        if line.contains("# "){
            println!("{}", line);
        }
        else if line.contains("- "){
            println!("{}", line)
        }
    }
    
}



fn project_standalone_terminal(project: Project, mut terminal: String){
    terminal = terminal.trim_end().to_owned();
    let mut profile = false;
    if terminal.contains("profile"){
        profile = true;
    }
    let terminal_vec:Vec<&str> = terminal.split(" ").collect();
    let mut terminal_start = process::Command::new(terminal_vec[0]);
    let mut first = true;
    for arg in terminal_vec{
        if first == true{
            first = false;
        }
        else{
            terminal_start.arg(arg);
        }
    } 
    if profile == false {
        terminal_start.arg(&project.boxname);
    }
    print!("{}", terminal);
    let start = terminal_start.spawn();
    match start{
        Ok(_child) => println!("New Terminal Started, you can retun to the menu now!"),
        Err(_error) => println!("error starting new terminanl, something may be wrong with the terminal part of your config!\nCheck ~/.conf/pyro_pentest_tool/conf for errors")
    }
    //process::Command::new("konsole").arg("--profile").arg("attack").arg(project.boxname).spawn().expect("error opeing konsole");
}


fn project_inline_terminal(project: Project){
    process::Command::new("distrobox").arg("enter").arg("--root").arg(project.boxname).arg("--").arg("script").arg("-a").arg("-B").arg("/pentest/working/terminal.log").status().expect("error opeing konsole");
}


fn gnerate_userpass(project: &Project){
    let mut outlines = Vec::new();
    let mut notes_file = project.notes_folder.clone();
    notes_file.push("l00t/creds.md");
    let loot_string = fs::read_to_string(notes_file).expect("error reading creds note");
    let clear_text = loot_string.split("# hashed").collect::<Vec<&str>>()[0];
    let clear_text_table = clear_text.split("| ----------------------------------- | ------------- | ----------------------------- |").collect::<Vec<&str>>()[1];
    let table_vec: Vec<&str> = clear_text_table.split("\n").collect();
    for line in table_vec{
        if line.len() > 1{
            let split_line: Vec<&str> = line.split("|").collect();
            let user = split_line[2].trim_end().trim_start();
            let password = split_line[3].trim_end().trim_start();
            let outline = format!("{}:{}\n", user, password);
            outlines.push(outline);
        }
    }
    let mut out_file_path = project.files_folder.clone();
    out_file_path.push("working/userpass_fromnotes.txt");
    let mut out_file = fs::File::create(out_file_path).expect("error creating userpass file");
    for line in outlines{
        out_file.write_all(line.as_bytes()).expect("error writing to userpass file");
    }
}

fn build_cmd_for_host_discovery(project: &Project){
    let mut cobalt_strike_response = String::new();
    let mut need_shell = false;
    println!("will you be running this via cobalt strike? (do you need it to start with \"shell\"?");
    let input_result = std::io::stdin().read_line(&mut cobalt_strike_response);
    if input_result.is_err(){
        println!("error getting user input... not really sure how you did this... just pressing enter would work..... wow");
        return;
    }
    if cobalt_strike_response.to_lowercase().contains("y"){
        need_shell = true;
    }
    let mut general_note_path = project.notes_folder.clone();
    general_note_path.push("general.md");
    println!("Reading from: {}", general_note_path.display());
    let mut ranges = Vec::new();
    let general_note_string = read_to_string(general_note_path);
    let mut _note_string = String::new();
   match general_note_string{
        Err(error) => {println!("error reading file to string!! {}", error); return;},
        _=> _note_string = general_note_string.unwrap()
    }
    let lines: Vec<&str> = _note_string.split("\n").collect();
    for line in lines{
       if line.contains("|"){
            if line.contains("."){
                let ip = line.split("|").collect::<Vec<&str>>()[1];
                if ip .contains(","){
                    let ips: Vec<&str> = ip.split(",").collect();
                    for ip in ips{
                        ranges.push(ip.trim_end().trim_start());
                    }
                } 
                else{
                    ranges.push(ip.trim_end().trim_start());
                }
            }
        }
    }
    let mut _discovery_command = "";
    _discovery_command = "(for /L %a IN (1,1,254) DO ping /n 1 /w 3 !!!.%a) | find \"Reply\"";
    let mut final_command = String::new();
    for range in ranges{
        let mut network: Vec<&str> = range.split(".").collect();
        network.pop();
        let network_string = network.join(".");
        let mut _range_command = String::new();
        if need_shell{
            _range_command = format!("{}{}","shell", _discovery_command.replace("!!!", &network_string));
            need_shell = false;
        }
        else{
            _range_command = _discovery_command.replace("!!!", &network_string);
        }
        final_command.push_str(_range_command.as_str());
        final_command.push_str(">> ping_only_replies.txt &");
    }
    final_command.pop();
    println!("{}", final_command);
}

fn run_initial_enum(project: &Project){
    let mut csv = String::new();
    println!("path to the csv?");
    std::io::stdin().read_line(&mut csv).unwrap();
    let status = process::Command::new("initial_recon").arg(&csv).arg(&project.customer).arg(&project.project_name).status().expect("error running initial_recon program");
    if status.success(){
        println!("execllent! hosts should be imported to {}/host_notes.md", &project.notes_folder.display());
    }
    else{
        println!("ooof something went wrong, host notes may not have saved correctly!");
    }
}

fn next_project_id(config_path: &PathBuf) -> i32{
    let projects = get_projects(config_path);
    let mut new_id = 0;
    for project in projects.clone(){
        if project.id > new_id{
            new_id = project.id + 1;
        }
    }
    return new_id;
}


fn main_menu(mut projects: Vec<Project>, config_path: PathBuf, base_files: &PathBuf, base_notes: &PathBuf, tools_dir: &PathBuf, boxtemplate: String, terminal: String){
    let mut loopize = true;
    let mut new_id = next_project_id(&config_path);
    loop {
        let active_project = get_active_project(&projects);
        let mut response = String::new();
        clear().expect("error clearing screen");
        print!("
,,,;;::ccccc::;;;::c::;,;::cccccllc::::::;:::;;;;,,;,'',,;,,;;;;;;;:;;;;;,,,,,,,,,,,'''''',,,,,,''''
,;;;::ccccc::::::ccc:;;;:ccccccclc::ccccccc::;;;;;;;;;;,,;;;;;;;;;;;;;;;,,,,,,,,,,,'''''''''',,,,,''
,;;:::ccc:cc:::ccc:::::::ccccclcccllccccllc::::::;;;;;;;;;;;;;;;;;;;;;;,,,,,,,,,,,''''''''...'',,,,'
,;;:::c::ccc::cc::::::::cclollllllolllllccccc::cc:::::;;;;;;;;;;;;;;;;;;,,,,,,,,,,'''''''''''..'',,,
,;::::::ccc::cc::::::ccloodollooooollllcccccc:llc::::::;;;;;;:;;;;;;;;;;;,,,,,,,,,,''''''''''''''',,
,;:::::c:::c::::ccccloddxxddxxddddodollllccclclcccccc:::::::::::::::;;;;;;;;,,,,,,,,,'''''''''''''',
;;:::::::c::c::clllodxxO0OKX0kkOkkxxxxxdooooolcccccccc:::::::cllc::::::::;;;;;,,,,,,,,,,'''''''''',,
;:::::c:cc::cclolclokO0KXNNX00KKK0O0KOxdxxdooccccclllccccccccdkdlcccccllcc::;;;;;;;;,,,,,,,,,,,',,,,
::::::cc::::coxdlllok00KNWNXXX0KXKOKNOkO0kddocccllllllccccclx0Kkodddoodddoollc::;;;;;;;;;,,,,,,,,,,,
:::::::c:::clkkodooxxkO0KX0xookKKkkKNKO0KkdoodolcllllollolldKNNXKKXKKKKKK0Okxdocc:cc:::;;;;;,,,,,,,,
::cc::cc::cldxllolodxxdoddc'.,okkxOXXOdxkxolkOdlllllllldkdokXNNNNNNNNX0kxollcc:::::cclc::;;;;;;,,,,,
:::::::cccldko:,.';cc:;:;....;clllOXOxxOkocoK0xooddollx0Odd0XNNNNNX0Oxdolcccc::;;;;;;:cllc:;;:;,,,,,
;;::c:::ccldkl;'...,''''....',;,';dxdkkdc;cONKxxOOOxddOXOdx0XXNNWNOdddxkOOOOkdllc:;,,,;cool:;;;;;,,;
,;;::;;::llco:,'..''..,.......''.';:ldl;,,:xXNOOXXX0xdkOOddkXNNWWWX00KXNNX0kxddddol:,''';lol:;;:;;,;
,,,;;;;;:coc;;'..;;. .,,;'.......':dxdc;ldc,l00xkXNKxodkkkkk0XNWWMWWWNXKOxdooolooool:;'..,lol::::;;;
',,,;;;;:cllc;,..',.  ','.  .....;odoo:;co:.'ldldOOx::x0KXX0kk0XNWWWXOxdoooollllllllcc:'..':lc:::;;;
',,,;;;;;:cccc:,. .          ..;cccccc:,,''.',,:l:;;:oOXXKOOOkxOXNNNXOxddooooollllllllc,....:c:::;;;
''',,,;;;;;;;cll,..   ..    .':lc:c:;,,......,,;:;;:cokkxxO00O0KXNNN0kxkkkxddoollllllll:'...':::::::
.''',,,,,,,,,;:c:,.. ..'.  ..','',;;'........',,;:;:::cdxxxddkKXXXKKKKXXXXXX0kdoloolllol;....,;:::::
..'''',,'',,,;;:::;..... ............... .'.....,;,',:ldc;:ldOKKK00KNWWWNNXK0xoooodooooo:'...';;;:;;
....'''''',,;;::cll:,''......  .      ..........'...,;;l:,,;oddkOOKNWWWWNX0kdodxxxxdddooc,...',;;;;,
......''''',;::cloodddol;.               ...........',.;;,,',:cxdd0KXXKKKXKOkxxkkkxdddooc,...';;,,,,
........''',;:clloddxxdo:'.              .. ...........''.'',;c:;cccodddk0KX0OOkxddddddo:...';;;;,,'
..........',;:cclodxxkxdl:,..          ...  ......'....'..':c,..'.,c,,,.,cxkO00Okxdddddc'..';:;;;,,'
..........',;;:cloodxkkkdol:'.    .  ...    ...... ......';c'.'...:;',;,'..,lxO00Oxxxo:'...,::;;,,,,
...........',;;:clodxkOOkxdol;.   ..  ..        ... ....',::'.''.',.........'oxdxxxdl;...';::;;;,,''
............',;:clodxkkOOOxddo;.   ......       ........',,',................';:clc;,...';::;;,,,'''
............',;:cldxkkOkkkxdddo;.    .....      .........,'...........'''','.',,'''....,cc:;;,,'''..
.............';:cldxxkkkkxddddxl,.   ....       .;c;'...................',;;cc;'...';clolc:;,,'''...
............'';clodxkkkkkxddddddl'    ...       .:lc;'................. ....',,''';lxkxdlc:;,'''....
........',,;:;coddxkOOOOOkxxddddd:.   ...     ..,''..................      . ..;cdkkkkxoc:;,'''.....
......',;::cllodxkkOOOOOOkxxxddddc.  ...      ..,;,'................... ..   .':odO0Okdl:;,'''......
.....',;:cloddxxkOOOOOOOkkxxdoooo;.  ..       .........................      .';cokOOxlc:;,''.......
....,;:clodxxkkOOOkO0OOOOxdlcc;;,......      .';,.................         ...',:ldxxxdlc;,''.......
...,:clodooxkkkO0OxO00OOxo:;;,. ........   .''.......... ..  ..           ..,,,;:codxxdlc:;,'.......
'',;clodolokOkxkOkkO00Oko:;;;.  ..... ..   .,,........'. ..  ..  ..   ..........;:codocclc:,,'......
              ___       __   __         ___               __        ___  __  
        |  | |__  |    /  ` /  \\  |\\/| |__     |__|  /\\  /  ` |__/ |__  |__) 
        |/\\| |___ |___ \\__, \\__/  |  | |___    |  | /~~\\ \\__, |  \\ |___ |  \\ 
                                                                             
         __   ___ ___     __                    __                           
        / _` |__   |     |__) |  | |\\ | | |\\ | / _`                          
        \\__> |___  |     |    |/\\| | \\| | | \\| \\__>     
    


NOTE SAVE PROJECT INFO BEFORE STOPPING THE APPLICATION, OR HOUR TRACKIGN WON'T BE ACCURATE
NOTE OPTION 10 WILL SAVE YOUR PROJECTS BEFORE QUITTING

Current Project: {} {}

        Main Menu:
            1 .) Show Active Project
            2 .) List Projects
            3 .) Switch Active Project
            4 .) create new project with Pyro's default tool
            5 .) Save Project Information
            6 .) Import New Project - and setup new Distrobox
            7 .) Remove Project
            8 .) Open A New Terminal in Current Active Project
            9 .) Open A Terminal In this windows for the current active project
            10.) Open Project Files Folder In Dolphin
            11.) Open Project Notes Folder In Dolphin
            12.) generate userpass file from your obsidian notes
            13.) run pyro's initail enum script on a nessus csv for the current project
            14.) Print Project Info For Report
            15.) Build host discovery cmd command from scope in notes
            16.) Stop All Distroboxes
            17.) Quit Application
\n", active_project.customer, active_project.project_name);
        std::io::stdin().read_line(&mut response).expect("error getting menu input");
        clear().expect("error clearing screen");
        match response.as_str().trim_end(){
            "1" => println!("\nclient: {}\n\nproject: {}\n\nbox: {}\n\nproject files: {}\n\nproject notes: {}\n", active_project.customer ,active_project.project_name, active_project.boxname, active_project.files_folder.display(), active_project.notes_folder.display()),
            "2" => {println!("+++++++++++++++++++++"); 
                    for project in &projects{
                        println!("++{}|{}++",project.customer ,project.project_name)}
                    println!("++++++++++++++++++++")},
            "3" => switch_project(&mut projects),
            "4" => start_pentest(),
            "5" => save_projects(&projects, &config_path),
            "6" => {new_id = new_id + 1; new_project(&mut projects, &base_files, &base_notes, &tools_dir, &boxtemplate, &config_path, new_id)},
            "7" => remove_project(&mut projects, &config_path),
            "8" => project_standalone_terminal(active_project.clone(), terminal.clone()),
            "9" => project_inline_terminal(active_project.clone()),
            "10" => open_in_dolphin("files", active_project.clone()),
            "11" => open_in_dolphin("notes", active_project.clone()),
            "12" => gnerate_userpass(&active_project),
            "13" => run_initial_enum(&active_project),
            "14" => print_report_information(active_project.clone()),
            "15" => build_cmd_for_host_discovery(&active_project),
            "16" => stop_all_boxes(&projects),
            "17" => {save_projects(&projects, &config_path);
                    let mut stop = String::new(); 
                    println!("stop all boxes?\ny/n");
                    std::io::stdin().read_line(&mut stop).unwrap();
                    if stop.contains("y"){
                        stop_all_boxes(&projects);
                    }
                    loopize = false},
            _ => println!("uknonwn selection")
        }
        if loopize == false{
            break
        }
        println!("\n\n\npress enter to return to the menu");
        let mut enter = String::new();
        std::io::stdin().read_line(&mut enter).unwrap();
    }
}


fn main() {
    print!("
    ⠀⠀⠀⣠⠶⠚⠛⠛⠛⠲⢦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⠀⠀⠀⣴⠟⠁⠀⠀⠀⠀⠀⠀⠀⠻⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⠀⣠⣾⣷⣄⠀⠀⠀⢀⣠⣤⣤⡀⠀⢿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⢸⣿⡿⢃⣸⡶⠂⢠⣿⣿⡿⠁⣱⠀⢸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⢸⡏⠉⠩⣏⣐⣦⠀⠛⠦⠴⠚⠁⠀⣸⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⣼⠧⠶⠶⠶⠿⠶⠶⠖⠚⠛⠉⠁⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠶⠶⡄⠀⠀
    ⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⢠⡟⠀⠀⢹⠀⠀
    ⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⢤⢠⡆⠀⢸⡄⠀⠀⠀⠀⠀⠀⢀⡿⠁⠀⠀⡾⠀⠀
    ⢹⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠈⡇⠀⠸⣧⣠⠴⠶⠖⠲⢶⡞⠁⠀⢈⡼⢃⠀⠀
    ⠸⡆⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⡇⠀⠀⢿⠁⠄⣲⡶⠶⠿⢤⣄⡀⠛⢛⠉⢻⠀
    ⠀⢿⡀⠀⠀⠀⠀⠀⠀⠀⢸⠠⣇⠀⠀⠀⠀⠊⠁⠀⠀⠀⠀⠀⠙⢦⠈⠙⠓⣆
    ⠀⠈⢷⡀⠀⠀⠀⠀⠀⢠⠏⡀⣬⣹⣦⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠈⡿⠶⠶⠋
    ⠀⠀⠈⢷⡀⠀⠀⠀⠀⠘⠛⠛⠋⠀⠀⠀⠀⠀⠀⠄⠀⠀⠀⠀⠀⣼⠃⠀⠀⠀
    ⠀⠀⠀⠀⠙⢦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠄⠀⠀⣠⡞⠁⠀⠀⠀⠀
    ⠀⠀⠀⠀⠀⠀⠈⠛⣷⢶⣦⣤⣄⣀⣠⣤⣤⠀⣶⠶⠶⠶⠛⠁⠀⠀⠀⠀⠀⠀
    ⠀⠀⠀⠀⣀⡀⠀⣰⠇⣾⠀⠀⠈⣩⣥⣄⣿⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⠀⠀⠀⠀⢿⡉⠳⡟⣸⠃⠀⠀⠀⠘⢷⣌⠉⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ⠀⠀⠀⠀⠀⠙⢦⣴⠏⠀⠀⠀⠀⠀⠀⠉⠳⠶⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
    ");
    let user_dirs = UserDirs::new().expect("error getting user directories");
    let mut config_path = user_dirs.home_dir().to_path_buf();
    config_path.push(".config/pyro_pentest_tool/conf");
    if config_path.as_path().exists() == false{
        install(&config_path);
    }
    let mut project_base_folder = PathBuf::new();
    let mut project_base_notes = PathBuf::new();
    let mut tools_folder = PathBuf::new();
    let mut terminal_command = String::new();
    let mut box_template = String::new();
    println!("\nconfig already generated\nloading config file...\n");
    let settings_string = fs::read_to_string(&config_path).expect("error reading config file");
    let settings: Vec<&str> = settings_string.split("\n").collect();
    for line in settings{
        if line.len() > 1{
            let setting_vec: Vec<&str> = line.split(":").collect();
            match setting_vec[0]{
                "Project_files" => project_base_folder.push(setting_vec[1].trim_end()),
                "Project_notes" => project_base_notes.push(setting_vec[1].trim_end()),
                "tools_folder" => tools_folder.push(setting_vec[1].trim_end()),
                "box_template" => box_template = setting_vec[1].trim_end().to_owned(),
                "terminal" => terminal_command = setting_vec[1].trim_end().to_owned(),
                _ => println!("error unknown setting: {}", setting_vec[0])
            }
        }
    }
    print!("
    Project Folders: {} 
    Note Folders: {}
    Tools Folder: {}
    distrobox template: {}
    terminal_command: {}\n
", project_base_folder.display(), project_base_notes.display(), tools_folder.display(), box_template, terminal_command);
    println!("loading project configs...");
    let projects = get_projects(&config_path);
    println!("Enter to start main menu");
    let mut enter = String::new();
    std::io::stdin().read_line(&mut enter).unwrap();
    main_menu(projects, config_path, &project_base_folder, &project_base_notes, &tools_folder, box_template, terminal_command);
}
