/*

This is a simple file downloader. It takes a file name as an argument and downloads it from the
server.

*/


use std::io::prelude::*;
use std::net::TcpStream;
use std::fs::File;
use std::path::Path;
use std::io::{BufReader, BufWriter};

fn main() {
    let mut args = std::env::args();
    args.next();
    let port = args.next().unwrap();
    let file_name = args.next().unwrap();
    let mut stream = TcpStream::connect("127.0.0.1:".to_string() + &port).unwrap();
    let mut file = File::open(&Path::new(&file_name)).unwrap();
    let mut reader = BufReader::new(&mut file);
    let mut writer = BufWriter::new(&mut stream);
    let mut buffer = [0; 1024];
    loop {
        let bytes_read = reader.read(&mut buffer).unwrap();
        if bytes_read == 0 {
            break;
        }
        writer.write(&buffer[..bytes_read]).unwrap();
        writer.flush().unwrap();
    }
}

------------------------------------------------------------------------------------------------------------

/*

This part is the simple HTTP server that serves files from the current directory.

*/




use std::io::prelude::*;
use std::net::TcpListener;
use std::fs::File;
use std::path::Path;
use std::io::{BufReader, BufWriter};

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
    for stream in listener.incoming() {
        let mut stream = stream.unwrap();
        let mut buffer = [0; 1024];
        stream.read(&mut buffer).unwrap();
        let mut file_name = String::from(&buffer[5..]);
        file_name.retain(|c| c != '\r' && c != '\n');
        let mut file = File::open(&Path::new(&file_name)).unwrap();
        let mut reader = BufReader::new(&mut file);
        let mut writer = BufWriter::new(&mut stream);
        let mut buffer = [0; 1024];
        loop {
            let bytes_read = reader.read(&mut buffer).unwrap();
            if bytes_read == 0 {
                break;
            }
            writer.write(&buffer[..bytes_read]).unwrap();
            writer.flush().unwrap();
        }
    }
}



/*

This allows us to turn any one of our current hosts into a new machine capable of updating new bins :)
 
Educational Purposes Only

*/