use std::env;
use pcap::*;

fn main() {
    let mut args = env::args();
    args.next();
    match args.next() {
        None => println!("No arg!"),
        Some(arg1) => match arg1.as_str() {
            "d" | "dump" => dump(),
            "p" | "pcap" => pcap(),
            _ => println!("Unknown arg: {}", arg1),
        }
    }
}

fn pcap() {
    let device = Device::lookup().unwrap();
    println!("Using device {}", device.name);

    let mut cap = Capture::from_device(device)
        .unwrap()
        .immediate_mode(true)
        .open()
        .unwrap();

    let mut savefile = cap.savefile("test.pcap").unwrap();

    for _ in 0..10 {
        let p = cap.next().unwrap();
        println!("packet received on network: {:?}", p);
        savefile.write(&p);
    }
    // let mut cap = Capture::from_file("test.pcap").unwrap();
    // let p = cap.next().unwrap();
    // println!("packet obtained from file: {:?}", p);
}

fn dump() {
    let device = Device::lookup().unwrap();
    println!("Using device {}", device.name);

    let mut cap = Capture::from_device(device)
        .unwrap()
        .immediate_mode(true)
        .open()
        .unwrap();

    loop {
        if let Ok(c) = cap.next() {
            println!("{:?}", c.header);
            println!("{:?}", c.data);
        }
    }
    // let stats = cap.stats().unwrap();
    // println!(
    //     "Received: {}, dropped: {}, if_dropped: {}",
    //     stats.received, stats.dropped, stats.if_dropped
    // );
}