// SPDX-FileCopyrightText: Heiko Schaefer <heiko@schaefer.name>
// SPDX-License-Identifier: MIT OR Apache-2.0

mod util;

use std::fs::File;
use std::path::PathBuf;

use anyhow::Result;
use clap::Parser;
use pgp::packet::PacketTrait;
use pgp::ser::Serialize;

#[derive(Parser, Debug)]
pub struct Args {
    #[command(subcommand)]
    pub cmd: Command,
}

#[derive(Parser, Debug)]
pub enum Command {
    /// Dump packet information
    Dump(DumpCommand),

    /// Split OpenPGP data into individual packets
    Split(SplitCommand),
}

#[derive(Parser, Debug)]
pub struct SplitCommand {
    /// Input file (stdin if unset)
    input: Option<PathBuf>,
}

#[derive(Parser, Debug)]
pub struct DumpCommand {
    /// Input file (stdin if unset)
    input: Option<PathBuf>,
}

fn main() -> Result<()> {
    let args = Args::parse();
    match args.cmd {
        Command::Dump(dc) => dump(dc.input)?,
        Command::Split(sc) => split(sc.input)?,
    }

    Ok(())
}

fn dump(input: Option<PathBuf>) -> Result<()> {
    for res in util::parse_packets(input)? {
        match res {
            Ok(p) => println!("{:#?}", p),
            Err(e) => println!("{:#?}", e),
        }
    }

    Ok(())
}

fn split(input: Option<PathBuf>) -> Result<()> {
    let prefix = input
        .clone()
        .and_then(|p| {
            p.file_name()
                .and_then(|os_str| os_str.to_str())
                .map(|str| str.to_string())
        })
        .map(|p| format!("{}-", p))
        .unwrap_or("".to_string());

    for (i, res) in util::parse_packets(input)?.enumerate() {
        match res {
            Ok(p) => {
                let filename = format!("{}{:06}-{:?}", prefix, i, p.tag());

                let mut file = File::create_new(filename)?;
                p.to_writer(&mut file)?;
            }
            Err(e) => println!("Error in packet {}: {:#?}", i, e),
        }
    }

    Ok(())
}
