//! Possible errors for SSH CA tool.

use crate::key::KeyError;
use crate::store::KeyStoreError;

use std::path::PathBuf;

/// Possible errors for SSH CA operations.
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum CAError {
    #[error("unknown store storage method {0}")]
    UnknownHow(String),

    #[error("failed to run the 'sopass' command to load store")]
    PassLoadInvoke(#[source] std::io::Error),

    #[error("failed to load store with the 'sopass' command:\n{0}")]
    PassLoadFailed(String),

    #[error("failed to run the 'sopass' command to save store")]
    PassSaveInvoke(#[source] std::io::Error),

    #[error("failed to feed the store to the 'sopass' command to save store")]
    PassSavePipe(#[source] std::io::Error),

    #[error("failed to feed the store to the 'sopass' command to save store")]
    PassSaveWait(#[source] std::io::Error),

    #[error("failed to save store with the 'sopass' command:\n{0}")]
    PassSaveFailed(String),

    #[error("unknown host CA: {0}")]
    NoSuchHostCA(String),

    #[error("unknown user CA: {0}")]
    NoSuchUserCA(String),

    #[error("unknown CA: {0}")]
    NoSuchCA(String),

    #[error("unknown host: {0}")]
    NoSuchHost(String),

    #[error("unknown user: {0}")]
    NoSuchUser(String),

    #[error("no private key stored for host {0}")]
    NoPrivateKey(String),

    #[error("problem with key")]
    KeyError(#[source] KeyError),

    #[error("problem with key store")]
    KeyStoreError(#[source] KeyStoreError),

    #[error("Could not read public key from {0}")]
    ReadPublicKey(PathBuf, #[source] std::io::Error),

    #[error("Could not read file {0} as UTF8")]
    Utf8(PathBuf, #[source] std::string::FromUtf8Error),

    #[error("Failed to read {0}")]
    ReadError(PathBuf, #[source] std::io::Error),

    #[error("Could not create directory {0}")]
    CreateDir(PathBuf, #[source] std::io::Error),

    #[error("Could not create file {0}")]
    Create(PathBuf, #[source] std::io::Error),

    /// Error writing a file.
    #[error("Couldn't write file {0}")]
    Write(PathBuf, #[source] std::io::Error),

    /// Error setting file permissions.
    #[error("Couldn't set permissions for file {0}")]
    SetPerm(PathBuf, #[source] std::io::Error),

    #[error("problem with YAML")]
    YamlError(#[source] serde_norway::Error),

    #[error("validity period is bad: {0:?}")]
    Validity(String),

    #[error("failed to generate JSON")]
    Json(#[source] serde_json::Error),

    #[error("failed to compute a time stamps a short time into the future")]
    ShortTime,

    #[error("failed to format timestamp")]
    TimeFormat(#[source] time::error::Format),

    #[error("host key for {0} has expired, only valid until {1}")]
    ExpiredHostKey(String, String),

    #[error("must give name of user to certify, or --all")]
    UserOrAll,

    #[error(transparent)]
    Config(#[from] crate::config::ConfigError),
}
