use std::env;
use std::fs::OpenOptions;

use mkfs_xfs::image::write_plan_to;
use mkfs_xfs::{FormatOptions, FormatPlan};

const DEFAULT_UUID: [u8; 16] = [
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
];

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = env::args().collect();
    if !(2..=4).contains(&args.len()) {
        eprintln!("usage: {} <image> [size-bytes] [sector-size]", args[0]);
        std::process::exit(2);
    }
    let size = args
        .get(2)
        .map(|arg| arg.parse())
        .transpose()
        .expect("size is a u64");
    let sector_size = args
        .get(3)
        .map(|arg| arg.parse())
        .transpose()
        .expect("sector size is a u32");

    let mut options = FormatOptions::new(size.unwrap_or(1 << 30), DEFAULT_UUID);
    if let Some(sector_size) = sector_size {
        options = options.with_sector_size(sector_size);
    }
    let plan = FormatPlan::new(options).expect("default plan is valid");

    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&args[1])?;
    file.set_len(plan.data_blocks() * u64::from(plan.block_size()))?;
    Ok(write_plan_to(&plan, &mut file)?)
}
