/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use anyhow::{Result, bail};
use rocksdb::DB;
use std::{env::args, fs::File, io::Read, path::Path};

fn main() -> Result<()> {
    let in_path = args().nth(1).unwrap();
    let out_path = args().nth(2).unwrap();
    let db = DB::open_default(out_path)?;
    if !in_path.ends_with("/") {
        bail!("path needs to end with /")
    }
    traverse(&db, &in_path, in_path.as_ref())?;
    db.flush()?;
    Ok(())
}

fn traverse(db: &DB, prefix: &str, path: &Path) -> Result<()> {
    if path.is_dir() {
        for e in path.read_dir()? {
            traverse(db, prefix, &e?.path())?;
        }
    }
    if path.is_file() {
        let key = path.to_string_lossy();
        let key = key.strip_prefix(prefix).unwrap();
        let mut value = Vec::new();
        File::open(path)?.read_to_end(&mut value)?;
        println!("{key}");
        db.put(key, value)?;
    }
    Ok(())
}
