//! Common definitions for the IP range output tool.
/*
 * Copyright (c) 2021  Peter Pentchev <roam@ringlet.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

use std::str::FromStr;

use anyhow::{anyhow, Error as AnyError};
use thiserror::Error;

/// An error that most likely occurred while parsing the IP address specifications.
#[allow(clippy::error_impl_error)]
#[derive(Debug, Error)]
pub enum Error {
    /// Invalid start address for a CIDR range.
    #[error("CIDR base address didn't start at subnet boundary")]
    CidrBadStart,

    /// Invalid offset for a CIDR range.
    #[error("CIDR offsets are between 0 and 32")]
    CidrPrefixTooLarge,

    /// Something went really, really wrong.
    #[error("prips internal error")]
    Internal(#[source] AnyError),

    /// Could not parse an IP address.
    #[error("Could not parse '{0}' as a valid IP address")]
    ParseAddress(String, #[source] AnyError),

    /// Could not parse an IP address / prefix length CIDR spec.
    #[error("Could not parse '{0}' as a valid CIDR specification")]
    ParseCidr(String, #[source] AnyError),

    /// Could not parse an exclusion mask.
    #[error("Could not parse '{0}' as a 0-255 integer value")]
    ParseExclude(String, #[source] AnyError),

    /// Invalid IP range specified.
    #[error("The start address must be smaller than the end address")]
    StartBeforeEnd,
}

/// An inclusive IPv4 address range.
#[derive(Debug)]
pub struct AddrRange {
    /// The first address in the range.
    pub start: u32,
    /// The last address in the range.
    pub end: u32,
}

/// The address formatting mode.
#[derive(Debug, Clone, Copy)]
pub enum AddrFormat {
    /// Dotted-quad.
    Dot,
    /// A single decimal number.
    Dec,
    /// A single hexadecimal number.
    Hex,
}

impl FromStr for AddrFormat {
    type Err = AnyError;
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "dot" => Ok(Self::Dot),
            "dec" => Ok(Self::Dec),
            "hex" => Ok(Self::Hex),
            _ => Err(anyhow!("Unrecognized address format specified")),
        }
    }
}

/// Exclude a set of IP addresses with the specified values for the specified octets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AddrExclude {
    /// The mask to apply a boolean "and" operation with.
    mask: u32,

    /// The octets to match after the boolean "and".
    value: u32,
}

impl AddrExclude {
    /// Construct an [`AddrExclude`] object with the specified mask and value.
    #[inline]
    #[must_use]
    pub const fn new(mask: u32, value: u32) -> Self {
        Self { mask, value }
    }

    /// The mask to apply a boolean "and" operation with.
    #[inline]
    #[must_use]
    pub const fn mask(self) -> u32 {
        self.mask
    }

    /// The octets to match after the boolean "and".
    #[inline]
    #[must_use]
    pub const fn value(self) -> u32 {
        self.value
    }
}

/// Runtime configuration for the IP range output tool.
#[derive(Debug)]
pub struct Config {
    /// The delimiter between two successive IP addresses.
    pub delim: char,
    /// The patterns of IP addresses to exclude when outputting a range.
    pub exclude: Option<Vec<AddrExclude>>,
    /// The address formatting mode.
    pub format: AddrFormat,
    /// The address range to process.
    pub range: AddrRange,
    /// The loop step.
    pub step: usize,
}
