+use std::{
+ net::{IpAddr, Ipv4Addr},
+ thread, time,
+};
+
+use serde_json::{json, Value};
+
+use crate::{
+ config::Config,
+ error::{Error, Result},
+};
+
+mod config;
+mod error;
+
+const FILE_CONF: &str = "config.ron";
+
+fn main() -> Result<()> {
+ println!("GANDI LiveDNS updater");
+
+ let config = Config::read(FILE_CONF)?;
+
+ println!(
+ "Configuration: {:?}",
+ Config {
+ api_key: String::from("*****"),
+ ..config.clone()
+ }
+ );
+
+ loop {
+ let time_beginning_loop = time::Instant::now();
+
+ if let Err(err) = check_and_update_dns(&config.api_key, &config.domains, config.ttl) {
+ println!("!! {}", err);
+ }
+
+ let elapsed = time::Instant::now() - time_beginning_loop;
+
+ if elapsed < config.delay_between_check {
+ let to_wait = config.delay_between_check - elapsed;
+ thread::sleep(to_wait);
+ }
+ }
+}
+
+fn check_and_update_dns(api_key: &str, domains: &Vec<(String, String)>, ttl: i32) -> Result<()> {
+ let real_ip = get_real_ip()?;
+
+ for (hostname, domain) in domains {
+ let current_ip = get_current_record_ip(api_key, hostname, domain)?;
+
+ if real_ip != current_ip {
+ println!(
+ "IP addresses don't match for domain {}: real = {}, dns = {}. Renewing DNS...",
+ domain, real_ip, current_ip
+ );
+ update_record_ip(api_key, hostname, domain, real_ip, ttl)?;
+ println!("Renewing of {}.{} successfully", hostname, domain);
+ }
+ }
+
+ Ok(())
+}
+
+fn get_real_ip() -> Result<Ipv4Addr> {
+ let url = "https://api.ipify.org";
+ let client = reqwest::blocking::Client::new();
+
+ match client.get(url).send() {
+ Ok(resp) => {
+ if resp.status().is_success() {
+ let content = resp.text().unwrap();
+ match content.parse() {
+ Ok(IpAddr::V4(ip_v4)) => Ok(ip_v4),
+ _ => Err(Box::new(Error {
+ message: String::from("Can't parse IPv4 from ipify"),
+ })),
+ }
+ } else {
+ Err(Box::new(Error {
+ message: format!("Request unsuccessful to {}: {:#?}", url, resp),
+ }))
+ }
+ }
+ Err(error) => Err(Box::new(Error {
+ message: format!("Error during request to {}: {:?}", url, error),
+ })),
+ }