#![allow(dead_code)]
use std::ffi::OsStr;
use std::io;
use std::process::{Child, Command, Stdio};
use chrono::{DateTime, Utc};
use sameold::{MessageHeader, UnrecognizedEventCode};
pub fn spawn<C, A, B>(
cmd: C,
args: A,
header: &MessageHeader,
input_rate_str: &str,
) -> io::Result<Child>
where
C: AsRef<OsStr>,
B: AsRef<OsStr>,
A: IntoIterator<Item = B>,
{
let (issue_ts, purge_ts) = match header.issue_datetime(&Utc::now()) {
Ok(issue_ts) => (
time_to_unix_str(issue_ts),
time_to_unix_str(issue_ts + header.valid_duration()),
),
Err(_e) => ("".to_owned(), "".to_owned()),
};
let locations: Vec<&str> = header.location_str_iter().collect();
Command::new(cmd)
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.args(args)
.env(childenv::SAMEDEC_RATE, input_rate_str)
.env(childenv::SAMEDEC_MSG, header.as_str())
.env(childenv::SAMEDEC_ORG, header.originator_str())
.env(
childenv::SAMEDEC_ORIGINATOR,
header.originator().as_display_str(),
)
.env(childenv::SAMEDEC_EVT, header.event_str())
.env(childenv::SAMEDEC_EVENT, msg_to_event(&header))
.env(childenv::SAMEDEC_SIGNIFICANCE, msg_to_significance(header))
.env(childenv::SAMEDEC_LOCATIONS, locations.join(" "))
.env(childenv::SAMEDEC_ISSUETIME, issue_ts)
.env(childenv::SAMEDEC_PURGETIME, purge_ts)
.spawn()
}
mod childenv {
pub const SAMEDEC_RATE: &str = "SAMEDEC_RATE";
pub const SAMEDEC_MSG: &str = "SAMEDEC_MSG";
pub const SAMEDEC_ORG: &str = "SAMEDEC_ORG";
pub const SAMEDEC_ORIGINATOR: &str = "SAMEDEC_ORIGINATOR";
pub const SAMEDEC_EVT: &str = "SAMEDEC_EVT";
pub const SAMEDEC_EVENT: &str = "SAMEDEC_EVENT";
pub const SAMEDEC_SIGNIFICANCE: &str = "SAMEDEC_SIGNIFICANCE";
pub const SAMEDEC_LOCATIONS: &str = "SAMEDEC_LOCATIONS";
pub const SAMEDEC_ISSUETIME: &str = "SAMEDEC_ISSUETIME";
pub const SAMEDEC_PURGETIME: &str = "SAMEDEC_PURGETIME";
}
fn msg_to_event(msg: &MessageHeader) -> String {
match msg.event() {
Ok(evt) => evt.as_display_str().to_owned(),
Err(err) => format!("{}", err),
}
}
fn msg_to_significance(msg: &MessageHeader) -> &'static str {
match msg.event() {
Ok(evt) => evt.to_significance_level().as_str(),
Err(UnrecognizedEventCode::WithSignificance(sl)) => sl.as_str(),
Err(UnrecognizedEventCode::Unrecognized) => "",
}
}
fn time_to_unix_str(tm: DateTime<Utc>) -> String {
format!("{}", tm.format("%s"))
}
#[cfg(test)]
mod tests {
use super::*;
use sameold::MessageHeader;
#[test]
fn test_msg_to_significance() {
const MSG: &str = "ZCZC-WXR-RWT-012345-567890-888990+0351-3662322-NOCALL-";
let msg = MessageHeader::new(MSG).unwrap();
assert_eq!("T", msg_to_significance(&msg));
}
#[test]
fn test_time_to_unix_str() {
let dt: DateTime<Utc> = DateTime::parse_from_rfc2822("Wed, 18 Feb 2015 23:16:09 GMT")
.unwrap()
.into();
assert_eq!(time_to_unix_str(dt), "1424301369");
}
}