use std::fs::create_dir;
use std::io::{Result, ErrorKind};
use std::fs::File;
use sys_mount::{
    Mount,
    MountFlags
};

const PATH_MAX:u32 = 4096;
const NET_NS_DIR:&str = "/var/run/netns";
const PROC_NS_DIR:&str = "/proc/self/ns/net";

fn main() -> Result<()> {
    create_ns_dir()?;
    let nsdir = format!("{}/{}",NET_NS_DIR,"fake-net");
    File::create(nsdir.clone())?;
    bind_ns_file(nsdir)?;
    println!("end");
    Ok(())
}

fn create_ns_dir() -> Result<()> {
    match create_dir(NET_NS_DIR) {
        Err(e) if e.kind() != ErrorKind::AlreadyExists => {
            println!("entra 2");
            Err(e)
        },
        _ => {
            println!("entra 1");
            Ok(())
        },
    }
}

fn bind_ns_file(ns_file: String) -> Result<()> {
    match create_mount(ns_file) {
        Ok(_mount) => {
            println!("mount succes");
            Ok(())
        },
        Err(e) => Err(e),
    }
}

fn create_mount(ns_file: String) -> std::io::Result<Mount> {
    Mount::builder()
        .flags(MountFlags::BIND)
        .mount(PROC_NS_DIR, ns_file)
}
