use std::path::PathBuf;

use cebolla::*;

use poem::{Route, Server, endpoint::StaticFilesEndpoint};
use snafu::ResultExt;

#[tokio::main]
async fn main() -> Result<(), snafu::Whatever> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.len() < 2 {
        snafu::whatever!("expected service name and path arguments");
    }

    if !tokio::fs::try_exists(&args[1])
        .await
        .whatever_context("checking for directory")?
    {
        snafu::whatever!("Path does not exist: {}", &args[0]);
    }

    println!("Connecting to tor network");
    let tor = Tor::new(TorConfig::default())
        .await
        .whatever_context("unable to connect to tor network")?;
    println!("Connected!");
    let service = tor
        .service(&args[0])
        .whatever_context("unable to start tor service")?;
    println!(
        "Onion address: {}",
        service.onion_address().unwrap().display_unredacted()
    );

    let path = PathBuf::from(&args[1]);

    let app = Route::new().nest(
        "/",
        StaticFilesEndpoint::new(&path)
            .show_files_listing()
            .index_file("index.html"),
    );

    Server::new(service)
        .name("tor-file-server")
        .run(app)
        .await
        .whatever_context("app")?;
    Ok(())
}
