use std::io;
use std::fs;
use clap::{Arg, App, SubCommand};

fn main() {


    let matches = App::new("My Super Program")
    .about("Extracts zip files partially")
    .arg(Arg::with_name("filter")
         .short("f")
         .long("filter")
         .value_name("FILE")
         .help("only extract this file")
         .takes_value(true))
    .arg(Arg::with_name("ZIP")
         .help("Sets the input file to use")
         .required(true)
         .index(1))
    .get_matches();

    let archive = matches.value_of("ZIP").unwrap();
    let filter = matches.value_of("filter");


    let fname = std::path::Path::new(archive);
    let file = fs::File::open(&fname).unwrap();

    let mut archive = zip::ZipArchive::new(file).unwrap();

    for i in 0..archive.len() {
        let mut file = archive.by_index(i).unwrap();
        let outpath = file.sanitized_name();

        if let Some(f) = filter {
            if !file.name().contains(f) {
                continue;
            }
        }

        {
            let comment = file.comment();
            if !comment.is_empty() {
                println!("File {} comment: {}", i, comment);
            }
        }

        if (&*file.name()).ends_with('/') {
            println!("File {} extracted to \"{}\"", i, outpath.as_path().display());
            fs::create_dir_all(&outpath).unwrap();
        } else {
            println!("File {} extracted to \"{}\" ({} bytes)", i, outpath.as_path().display(), file.size());
            if let Some(p) = outpath.parent() {
                if !p.exists() {
                    fs::create_dir_all(&p).unwrap();
                }
            }
            let mut outfile = fs::File::create(&outpath).unwrap();
            io::copy(&mut file, &mut outfile).unwrap();
        }

        // Get and Set permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Some(mode) = file.unix_mode() {
                fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap();
            }
        }
    }
}