use std::fs::File;
use std::io::BufReader;
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use std::process::ExitCode;
use backhand::{FilesystemReader, FilesystemWriter, NodeHeader};
use backhand_cli::after_help;
use clap::Parser;
use tracing::{error, info};
use tracing_subscriber::EnvFilter;
#[cfg(all(target_env = "musl", target_pointer_width = "64"))]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
#[derive(Parser, Debug)]
#[command(author,
version,
name = "add-backhand",
after_help = after_help(false),
max_term_width = 98,
styles = clap_cargo::style::CLAP_STYLING,
)]
struct Args {
input_image: PathBuf,
#[clap(short, long)]
dir: bool,
#[clap(short, long)]
#[clap(required_unless_present = "dir")]
file: Option<PathBuf>,
#[clap(name = "FILE_PATH_IN_IMAGE")]
path: PathBuf,
output_image: PathBuf,
#[clap(long, required_if_eq("dir", "true"))]
mode: Option<u16>,
#[clap(long, required_if_eq("dir", "true"))]
uid: Option<u32>,
#[clap(long, required_if_eq("dir", "true"))]
gid: Option<u32>,
#[clap(long, required_if_eq("dir", "true"))]
mtime: Option<u32>,
#[clap(long)]
pad_len: Option<u32>,
#[clap(long)]
no_compression_options: bool,
}
fn main() -> ExitCode {
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("add=info"));
tracing_subscriber::fmt().with_env_filter(env_filter).init();
let args = Args::parse();
let file = File::open(args.input_image).unwrap();
let file = BufReader::new(file);
let filesystem = FilesystemReader::from_reader(file).unwrap();
let mut filesystem = FilesystemWriter::from_fs_reader(&filesystem).unwrap();
if let Some(file) = args.file {
let new_file = File::open(&file).unwrap();
let meta = file.metadata().unwrap();
let mode = args.mode.unwrap_or(meta.mode() as u16) & 0xfff;
let uid = args.uid.unwrap_or(meta.uid());
let gid = args.gid.unwrap_or(meta.gid());
let mtime = args.mtime.unwrap_or(meta.mtime() as u32);
let node = NodeHeader::new(mode, uid, gid, mtime);
if let Err(e) = filesystem.push_file(new_file, args.path, node) {
error!("{e}");
return ExitCode::FAILURE;
}
} else if args.dir {
let node = NodeHeader::new(
args.mode.unwrap(),
args.uid.unwrap(),
args.gid.unwrap(),
args.mtime.unwrap(),
);
if let Err(e) = filesystem.push_dir(args.path, node) {
error!("{e}");
return ExitCode::FAILURE;
}
}
if let Some(pad_len) = args.pad_len {
filesystem.set_kib_padding(pad_len)
}
if args.no_compression_options {
filesystem.set_emit_compression_options(false);
}
let Ok(output) = File::create_new(&args.output_image) else {
error!("failed to open {}", args.output_image.display());
return ExitCode::FAILURE;
};
if let Err(e) = filesystem.write(output) {
error!("{e}");
}
info!("added file and wrote to {}", args.output_image.display());
ExitCode::SUCCESS
}