use anyhow::Result;

use clap::ValueEnum;
use clap_complete::Shell;

use sequoia_man::asset_out_dir;

pub mod cli {
    include!("src/cli/mod.rs");
}

// To avoid adding a build dependency on sequoia-openpgp, we mock the
// bits of openpgp that the CLI module uses.
pub mod openpgp {
    #[derive(Clone, Debug)]
    pub struct KeyHandle {
    }

    impl From<&str> for KeyHandle {
        fn from(_: &str) -> KeyHandle {
            KeyHandle {}
        }
    }
}

fn main() {
    let mut cli = cli::build(false);
    generate_shell_completions(&mut cli).unwrap();
    generate_man_pages(&mut cli).expect("can generate man pages");
}

/// Generates shell completions.
fn generate_shell_completions(cli: &mut clap::Command) -> Result<()> {
    let path = asset_out_dir("shell-completions")?;

    for shell in Shell::value_variants() {
        clap_complete::generate_to(*shell, cli, "sq-git", &path)?;
    }

    println!("cargo:warning=shell completions written to {}", path.display());
    Ok(())
}

/// Generates man pages.
fn generate_man_pages(cli: &mut clap::Command) -> Result<()> {
    let version = env!("CARGO_PKG_VERSION");
    let mut builder = sequoia_man::man::Builder::new(cli, version, None);
    builder.see_also(
        &[ "For the full documentation see <https://sequoia-pgp.gitlab.io/sequoia-git>." ]);

    let man_pages = asset_out_dir("man-pages")?;

    sequoia_man::generate_man_pages(&man_pages, &builder).unwrap();
    Ok(())
}
