nazara 0.2.0

A CLI application to create and update machines and VMs in NetBox.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! This module is responsible for creating a default configuration file as well as validating and reading the config
//! file.
//!
//! ```toml
#![doc = include_str!("config_template.toml")]
//! ```
//!
//! It will be created at ` $HOME/.config/nazara/config.toml`.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fs::File;
use std::io::Write;
use std::io::prelude::*;
use std::path::Path;
use std::{fs, path::PathBuf};

use super::util::*;
use crate::error::*;

/// Configuration state set by the configuration file.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConfigData {
    /// Configuration parameters for the NetBox connection.
    pub netbox: NetboxConfig,
    /// Common parameters.
    pub common: CommonConfig,
    #[serde(flatten)]
    pub machine: MachineConfig,
}

/// Configuration parameters relevant for a NetBox connection.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NetboxConfig {
    /// The API token required for authentication.
    pub netbox_api_token: String,
    /// The base URL of your NetBox instance. (e.g <https://netbox.yourorg.com>)
    pub netbox_uri: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CommonConfig {
    pub name: Option<String>,
    pub description: String,
    pub comments: String,
    pub status: String,
    #[serde(default)]
    pub primary_ip4: Option<String>,
    #[serde(default)]
    pub primary_ip6: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum MachineConfig {
    #[serde(rename = "device")]
    Device(DeviceConfig),
    #[serde(rename = "vm")]
    VM(VmConfig),
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DeviceConfig {
    pub device_type: i64,
    pub role: i64,
    pub site: i64,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VmConfig {
    pub cluster: i64,
}

/// View config file.
///
/// # Returns
///
/// Either `Ok(())` or `NazaraError` depending on operation outcome.
pub fn view_config_file() -> NazaraResult<()> {
    let config_path = get_config_path(true);

    if !Path::new(&config_path).exists() {
        warn!(
            "No config file found at '{}' use 'nazara write-config' to write a new one.",
            config_path.display()
        );
        return Ok(());
    }

    let contents = fs::read_to_string(&config_path).map_err(NazaraError::FileOpError)?;

    // Parse as TOML for formatting
    let parsed: toml::Value =
        toml::from_str(&contents).map_err(NazaraError::DeserializationError)?;

    let pretty = toml::to_string_pretty(&parsed).map_err(NazaraError::SerializationError)?;

    println!("\n=== Current Nazara Configuration ===\n");
    println!("{}", pretty);
    println!("==================================\n");

    Ok(())
}

/// Write the configuration file when the `write-config` command is used.
/// **Overrides current config if it already exists.** Use the `--uri` and
/// `--token` CLI flags to override them temporarily.
///
/// # Parameters
///
/// * `uri: &str` - The URI of the NetBox instance.
/// * `token: &str` - The authentication token for NetBox.
/// * `name: Option<&String>` - The name of the machine.
/// * `description: Option<&String>` - A description of the machine. (optional)
/// * `comments: Option<&String>` - A comment for the entry. (optional)
/// * `status: Option<&String>` - Status of the machine. (optional; default: 'active')
/// * `device_type: Option<&i64>` - ID of the device type.
/// * `role: Option<&i64>` - ID of the machine's role
/// * `site: Option<&i64>` - ID of the site. (physical devices only)
/// * `cluster: Option<&i64>` - ID of the cluster. (VMs only)
/// * `json: Option<&String>` - JSON representation of desired configuration values. (Optional; exclusive with all other parameters)
///
/// # Returns
///
/// Either `Ok(())` or `NazaraError` depending on operation outcome.
pub fn write_config_file(
    uri: &Option<String>,
    token: &Option<String>,
    name: &Option<String>,
    description: &Option<String>,
    comments: &Option<String>,
    status: &Option<String>,
    primary_ip4: &Option<String>,
    primary_ip6: &Option<String>,
    device_type: &Option<i64>,
    role: &Option<i64>,
    site: &Option<i64>,
    cluster: &Option<i64>,
    force: &bool,
    json: &Option<String>,
) -> NazaraResult<()> {
    let config_path = get_config_path(true);
    let config_dir = get_config_path(false);

    fs::create_dir_all(&config_dir).map_err(NazaraError::FileOpError)?;

    if let Some(json_str) = json {
        return write_config_from_json(&config_path, &json_str);
    }

    if file_exists(&config_path) && !force {
        update_existing_config(
            &config_path,
            uri,
            token,
            name,
            description,
            comments,
            status,
            primary_ip4,
            primary_ip6,
            device_type,
            role,
            site,
            cluster,
        )
    } else {
        create_new_config(
            &config_path,
            uri,
            token,
            name,
            description,
            comments,
            status,
            device_type,
            role,
            site,
            cluster,
        )
    }
}

/// Check presence and validity of config file.
pub fn check_config_file() -> NazaraResult<()> {
    let config_path = get_config_path(true);
    if !file_exists(&config_path) {
        return Err(NazaraError::Other(
            "[Error] Configuration file does not exist!".into(),
        ));
    }
    status!("Checking integrity of config file...");
    ConfigData::validate_config_file(ValidationMode::Soft)?;
    success!("Configuration file valid!");
    Ok(())
}

/// Create new config file with given parameters.
///
/// # Parameters
/// * `config_path: &Path` - The path to the config directory.
/// * `uri: &str` - The URI of the NetBox instance.
/// * `token: &str` - The authentication token for NetBox.
/// * `description: Option<String>` - Optional description of the machine.
/// * `comments: Option<String>` - Optional comments for the entry.
/// * `status: Option<String>` - Status of the device or VM.
/// * `device_tpye: Option<String>` - The status of the machine. (default: 'active')
/// * `role: Option<i64>` - The ID of the device role. (physical devices only)
/// * `site: Option<i64>` - The ID of the site where the device is located. (physical devices only)
/// * `cluster: Option<i64>` - The ID of the VM cluster. (VMs only)
///
/// # Returns
///
/// `Ok(())` or `NazaraError` depending on operation outcome.
fn create_new_config(
    config_path: &std::path::Path,
    uri: &Option<String>,
    token: &Option<String>,
    name: &Option<String>,
    description: &Option<String>,
    comments: &Option<String>,
    status: &Option<String>,
    device_type: &Option<i64>,
    role: &Option<i64>,
    site: &Option<i64>,
    cluster: &Option<i64>,
) -> NazaraResult<()> {
    let mut contents = include_str!("config_template.toml").to_string();

    if let Some(v) = token {
        contents = contents.replace(
            "netbox_api_token = \"\"",
            &format!("netbox_api_token = \"{}\"", v),
        );
    }
    if let Some(v) = uri {
        contents = contents.replace("netbox_uri = \"\"", &format!("netbox_uri = \"{}\"", v));
    }
    if let Some(v) = name {
        contents = contents.replace("name = \"\"", &format!("name = \"{}\"", v));
    }
    if let Some(v) = description {
        contents = contents.replace("description = \"\"", &format!("description = \"{}\"", v));
    }
    if let Some(v) = comments {
        contents = contents.replace(
            "comments = \"Automatically registered by Nazara.\"",
            &format!("comments = \"{}\"", v),
        );
    }
    if let Some(v) = status {
        contents = contents.replace("status = \"active\"", &format!("status = \"{}\"", v));
    }

    // Machine-specific section
    if device_type.is_some() || role.is_some() || site.is_some() {
        contents = uncomment_section(contents, "device");
        if !contents.contains("[device]") {
            contents.push_str("\n[device]\n");
        }
        contents = uncomment_key(contents, "device", "device_type");
        contents = uncomment_key(contents, "device", "role");
        contents = uncomment_key(contents, "device", "site");
        if let Some(v) = device_type {
            contents = replace_key(contents, "device", "device_type", &v.to_string());
        }
        if let Some(v) = role {
            contents = replace_key(contents, "device", "role", &v.to_string());
        }
        if let Some(v) = site {
            contents = replace_key(contents, "device", "site", &v.to_string());
        }
        contents = comment_out_key(contents, "vm", "cluster");
        contents = comment_out_section(contents, "vm");
    } else if let Some(c) = cluster {
        contents = uncomment_section(contents, "vm");
        if !contents.contains("[vm]") {
            contents.push_str("\n[vm]\n");
        }
        contents = uncomment_key(contents, "vm", "cluster");
        contents = replace_key(contents, "vm", "cluster", &c.to_string());
        contents = comment_out_key(contents, "device", "device_type");
        contents = comment_out_key(contents, "device", "role");
        contents = comment_out_key(contents, "device", "site");
        contents = comment_out_section(contents, "device")
    }

    // Write final file
    let mut file = File::create(config_path).map_err(NazaraError::FileOpError)?;
    file.write_all(contents.as_bytes())
        .map_err(NazaraError::FileOpError)?;

    status!("Checking integrity of the file...");
    ConfigData::validate_config_file(ValidationMode::Soft)?;
    Ok(())
}

/// Update existing TOML file in place, replacing only provided keys.
///
/// # Parameters
/// * `config_path: &Path` - The path to the config directory.
/// * `uri: &str` - The URI of the NetBox instance.
/// * `token: &str` - The authentication token for NetBox.
/// * `description: Option<String>` - Optional description of the machine.
/// * `comments: Option<String>` - Optional comments for the entry.
/// * `status: Option<String>` - Status of the device or VM.
/// * `device_tpye: Option<String>` - The status of the machine. (default: 'active')
/// * `role: Option<i64>` - The ID of the device role. (physical devices only)
/// * `site: Option<i64>` - The ID of the site where the device is located. (physical devices only)
/// * `cluster: Option<i64>` - The ID of the VM cluster. (VMs only)
///
/// # Returns
///
/// `Ok(())` or `NazaraError` depending on operation outcome.
fn update_existing_config(
    config_path: &std::path::Path,
    uri: &Option<String>,
    token: &Option<String>,
    name: &Option<String>,
    description: &Option<String>,
    comments: &Option<String>,
    status: &Option<String>,
    primary_ip4: &Option<String>,
    primary_ip6: &Option<String>,
    device_type: &Option<i64>,
    role: &Option<i64>,
    site: &Option<i64>,
    cluster: &Option<i64>,
) -> NazaraResult<()> {
    let mut contents = fs::read_to_string(config_path).map_err(NazaraError::FileOpError)?;

    if let Some(v) = token {
        contents = replace_key(contents, "netbox", "netbox_api_token", &v);
    }
    if let Some(v) = uri {
        contents = replace_key(contents, "netbox", "netbox_uri", &v);
    }
    if let Some(v) = name {
        contents = replace_key(contents, "common", "name", &v);
    }
    if let Some(v) = description {
        contents = replace_key(contents, "common", "description", &v);
    }
    if let Some(v) = comments {
        contents = replace_key(contents, "common", "comments", &v);
    }
    if let Some(v) = status {
        contents = replace_key(contents, "common", "status", &v);
    }
    if let Some(v) = primary_ip4 {
        contents = replace_key(contents, "common", "primary_ip4", v);
    }
    if let Some(v) = primary_ip6 {
        contents = replace_key(contents, "common", "primary_ip6", v);
    }

    // Machine-specific
    if device_type.is_some() || role.is_some() || site.is_some() {
        contents = uncomment_section(contents, "device");
        if !contents.contains("[device]") {
            contents.push_str("\n[device]\n");
        }
        contents = uncomment_key(contents, "device", "device_type");
        contents = uncomment_key(contents, "device", "role");
        contents = uncomment_key(contents, "device", "site");
        if let Some(v) = device_type {
            contents = replace_key(contents, "device", "device_type", &v.to_string());
        }
        if let Some(v) = role {
            contents = replace_key(contents, "device", "role", &v.to_string());
        }
        if let Some(v) = site {
            contents = replace_key(contents, "device", "site", &v.to_string());
        }
        contents = comment_out_key(contents, "vm", "cluster");
        contents = comment_out_section(contents, "vm")
    } else if let Some(c) = cluster {
        contents = uncomment_section(contents, "vm");
        if !contents.contains("[vm]") {
            contents.push_str("\n[vm]\n");
        }
        contents = uncomment_key(contents, "vm", "cluster");
        contents = replace_key(contents, "vm", "cluster", &c.to_string());
        contents = comment_out_key(contents, "device", "device_type");
        contents = comment_out_key(contents, "device", "role");
        contents = comment_out_key(contents, "device", "site");
        contents = comment_out_section(contents, "device")
    }

    fs::write(config_path, contents).map_err(NazaraError::FileOpError)?;
    status!("Checking integrity of the file...");
    ConfigData::validate_config_file(ValidationMode::Soft)?;
    success!(
        "Updated existing configuration at {} (preserved comments)",
        config_path.display()
    );
    Ok(())
}

/// Write config file from JSON blob.
///
/// # Parameters
///
/// * `config_path: &Path` - The path of the config directory.
/// * `json_str: &str` - The pure JSON blob from command line.
///
/// # Returns
///
/// `Ok(())` or `NazaraError` depending on operation outcome.
fn write_config_from_json(config_path: &std::path::Path, json_str: &str) -> NazaraResult<()> {
    let parsed: Value = serde_json::from_str(json_str).map_err(NazaraError::JsonParse)?;

    let nb_uri = parsed
        .get("netbox")
        .and_then(|key| key.get("netbox_uri"))
        .and_then(|value| value.as_str())
        .unwrap_or_default();

    let nb_token = parsed
        .get("netbox")
        .and_then(|key| key.get("netbox_api_token"))
        .and_then(|value| value.as_str())
        .unwrap_or_default();

    let mut contents = include_str!("config_template.toml").to_string();
    contents = contents.replace("netbox_uri = \"\"", &format!("netbox_uri = \"{}\"", nb_uri));
    contents = contents.replace(
        "netbox_api_token = \"\"",
        &format!("netbox_api_token = \"{}\"", nb_token),
    );

    if let Some(common) = parsed.get("common") {
        if let Some(name) = common.get("name").and_then(|v| v.as_str()) {
            contents = contents.replace("name = \"\"", &format!("name = \"{}\"", name));
        }
        if let Some(desc) = common.get("description").and_then(|v| v.as_str()) {
            contents =
                contents.replace("description = \"\"", &format!("description = \"{}\"", desc));
        }
        if let Some(comment) = common.get("comments").and_then(|v| v.as_str()) {
            contents = contents.replace(
                "comments = \"Automatically registered by Nazara.\"",
                &format!("comments = \"{}\"", comment),
            );
        }
        if let Some(status) = common.get("status").and_then(|v| v.as_str()) {
            contents = contents.replace("status = \"active\"", &format!("status = \"{}\"", status));
        }
        if let Some(ip4) = common.get("primary_ip4").and_then(|v| v.as_str()) {
            contents =
                contents.replace("primary_ip4 = \"\"", &format!("primary_ip4 = \"{}\"", ip4));
        }
        if let Some(ip6) = common.get("primary_ip6").and_then(|v| v.as_str()) {
            contents =
                contents.replace("primary_ip6 = \"\"", &format!("primary_ip6 = \"{}\"", ip6));
        }
    }

    if let Some(device) = parsed.get("device") {
        let device_type = device
            .get("device_type")
            .and_then(|v| v.as_i64())
            .unwrap_or(0);
        let role = device.get("role").and_then(|v| v.as_i64()).unwrap_or(0);
        let site = device.get("site").and_then(|v| v.as_i64()).unwrap_or(0);
        contents.push_str(&format!(
            "\n[device]\ndevice_type = {}\nrole = {}\nsite = {}\n",
            device_type, role, site
        ));
    } else if let Some(vm) = parsed.get("vm") {
        let cluster = vm.get("cluster").and_then(|v| v.as_i64()).unwrap_or(0);
        contents.push_str(&format!("\n[vm]\ncluster = {}\n", cluster));
    }

    fs::write(config_path, contents).map_err(NazaraError::FileOpError)?;
    success!(
        "Configuration written (JSON mode) to '{}'",
        config_path.display()
    );
    Ok(())
}

/// This function reads the configuration file located at `$HOME/.config/nazara/config.toml`.
/// If no file can be found, a warning is displayed to the user and a default config file is written.
/// If command line arguments are given, the parameters read from the file will be overwritten.
///
/// # Parameters
/// - `uri`: The URI of the NetBox instance
/// - `token`: The API tokent to be used
/// - `name`: The name of the machine to register
pub fn set_up_configuration(uri: Option<&str>, token: Option<&str>) -> NazaraResult<ConfigData> {
    let mut conf_data;

    status!("Checking for existing configuration file...");

    if file_exists(&get_config_path(true)) {
        info!("Configuration file already exists. Validating...");
        ConfigData::validate_config_file(ValidationMode::Strict)?;
        success!("Configuration file valid. Loading defaults...");
        conf_data = ConfigData::read_config_file()?;

        if let Some(x) = uri {
            conf_data.netbox.netbox_uri = x.to_owned();
        }

        if let Some(x) = token {
            conf_data.netbox.netbox_api_token = x.to_owned();
        }

        return Ok(conf_data);
    }

    info!("No config file found. Creating default...");

    ConfigData::initialize_config_file(uri, token)?;
    success!("Default configuration file created successfully.");

    if uri.is_none() || token.is_none() {
        return Err(NazaraError::MissingConfigOptionError(String::from(
            "netbox_uri, netbox_token",
        )));
    }

    conf_data = ConfigData::read_config_file()?;

    if let (Some(u), Some(t)) = (uri, token) {
        conf_data.netbox.netbox_uri = u.to_owned();
        conf_data.netbox.netbox_api_token = t.to_owned();
    }

    success!("Configuration loaded.");
    Ok(conf_data)
}

/// Checks if a config file exists at a given path.
/// Returns true if the file exists.
///
/// # Parameters
/// - `path`: The filepath to check.
///
/// # Returns
/// True if the file exists.
fn file_exists(path: &Path) -> bool {
    if let Ok(metadata) = fs::metadata(path) {
        metadata.is_file()
    } else {
        false
    }
}

/// Constructs a path to the config directory.
/// This function will fetch the path to the home directory from the `$HOME` environment variable.
///
/// # Panics
/// This function panics if no `$HOME` variable can be found.
fn get_config_path(with_file: bool) -> PathBuf {
    let home_dir = std::env::var("HOME").expect("No $HOME variable found!");
    if with_file {
        return Path::new(&home_dir).join(".config/nazara/config.toml");
    }
    Path::new(&home_dir).join(".config/nazara/")
}

/// Not every process requires involving config validation
/// requires Nazara to abort. Instead we decide how strictly
/// to validate and warn/fail depending on context.
#[derive(Debug, Clone, Copy)]
pub enum ValidationMode {
    Soft,
    Strict,
}

impl ConfigData {
    /// Initializes a new default configuration file if none exists.
    ///
    /// # Parameters
    /// - `uri`: The URI of the NetBox instance
    /// - `token`: The API tokent to be used
    /// - `name`: The name of the machine to register
    fn initialize_config_file(uri: Option<&str>, token: Option<&str>) -> NazaraResult<()> {
        let file = include_str!("config_template.toml");
        let mut contents = file.to_owned();

        // Replace placeholders with actual values if exist.
        if let Some(uri) = uri {
            contents = contents.replace("{NETBOX_URI}", uri);
        }
        if let Some(token) = token {
            contents = contents.replace("{NETBOX_TOKEN}", token);
        }

        // Path to the output file
        let config_path = get_config_path(false);
        std::fs::create_dir_all(&config_path).map_err(NazaraError::FileOpError)?;
        let mut output_file =
            File::create(config_path.join("config.toml")).map_err(NazaraError::FileOpError)?;

        output_file
            .write_all(contents.as_bytes())
            .map_err(|e| NazaraError::FileOpError(e))?;

        Ok(())
    }

    /// Looks for a config file at the standard location and check if it is valid.
    /// If it is not or does not exists, an error is returned.
    fn validate_config_file(mode: ValidationMode) -> NazaraResult<()> {
        let mut file = File::open(get_config_path(true)).map_err(NazaraError::FileOpError)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .map_err(|e| NazaraError::FileOpError(e))?;

        // checks if the type, role, site, and cluster fields exist and warns/errors depending on the answer
        let config_unwrapped: Value = toml::from_str(&contents).unwrap();
        let config_objects: [&str; 2] = ["device", "vm"]; //config entries to check for
        let config_objects_device: [&str; 3] = ["device_type", "role", "site"]; //entries under "device" to check for
        let mut config_check_results: [bool; 2] = [false; 2];
        let mut config_error = false;
        let mut config_zero = false;
        for i in 0..2 {
            if config_unwrapped.get(config_objects[i]).is_some() {
                config_check_results[i] = true;
            }
        }

        // throws a warning/errror if both a device and a vm config exist or both dont exist.
        if config_check_results[0] && config_check_results[1] {
            NazaraError::Other("Both a VM and Device Config exist".to_owned()).log(None);
            config_error = true;
        } else if !config_check_results[0] && !config_check_results[1] {
            NazaraError::Other("Neither Device Config nor VM Config exists".to_owned()).log(None);
            config_error = true;
        }

        // checks in more detail if the device configs are all correct
        if config_check_results[0] {
            for i in 0..3 {
                if config_unwrapped[config_objects[0]]
                    .get(config_objects_device[i])
                    .is_none()
                {
                    let err = NazaraError::Other(format!(
                        "Device field exists but '{}' is empty",
                        config_objects_device[i]
                    ));
                    err.log(None);
                    config_error = true;
                } else if config_unwrapped[config_objects[0]]
                    .get(config_objects_device[i])
                    .unwrap()
                    == 0
                {
                    let string = format!(
                        "Device field exists but '{}' is 0",
                        config_objects_device[i]
                    );
                    warn!("{}", string);
                    config_zero = true;
                }
            }
        }
        // checks in more detail if the vm configs are all correct
        if config_check_results[1] {
            if config_unwrapped[config_objects[1]].get("cluster").is_none() {
                NazaraError::Other("VM field exists but 'cluster' is empty".to_owned()).log(None);
                config_error = true;
            } else if config_unwrapped[config_objects[1]].get("cluster").unwrap() == 0 {
                warn!("VM field exists but 'cluster' is 0");
                config_zero = true;
            }
        }

        //errors out if something is very wrong with the config, warns if a change needs to be made, otherwise continues
        if config_error {
            return Err(NazaraError::Other("Incorrect Config options".to_owned()));
        } else if config_zero {
            warn!("Device/VM config is syntactically valid, but values set to 0 must be changed")
        } else {
            success!("Device/VM config is valid")
        }

        // this is the part that aborts if device/vm config is incorrect
        let config_data: ConfigData =
            toml::from_str(&contents).map_err(NazaraError::DeserializationError)?;

        // checks the uri and api token, creating a string of the missing configs for later errors
        let mut error_string: String = String::from("");
        if config_data.netbox.netbox_uri.is_empty() {
            warn!("Missing required config option: 'netbox_uri'");
            config_error = true;
            error_string.push_str("netbox_uri ");
        }
        if config_data.netbox.netbox_api_token.is_empty() {
            warn!("Missing required config option: 'netbox_api_token'");
            config_error = true;
            error_string.push_str("netbox_api_token");
        }

        if config_zero {
            match mode {
                ValidationMode::Soft => {
                    warn!("Config file contains invalid Entries");
                }
                ValidationMode::Strict => {
                    return NazaraError::Other("Config file contains invalid entries".to_owned())
                        .fail();
                }
            }
        }

        // prints a warning in soft mode and aborts in strict mode
        if config_error {
            match mode {
                ValidationMode::Soft => {
                    warn!("Config is missing required Netbox config options");
                }
                ValidationMode::Strict => {
                    return NazaraError::MissingConfigOptionError(String::from("netbox_api_token"))
                        .fail();
                }
            }
        }

        Ok(())
    }

    /// Opens and reads the config file and writes the set parameters into a
    /// [`ConfigData`] object, which is then returned.
    fn read_config_file() -> NazaraResult<ConfigData> {
        let mut file = File::open(get_config_path(true))?;

        let mut contents = String::new();
        file.read_to_string(&mut contents)?;

        toml::from_str(&contents).map_err(|x| x.into())
    }

    /// Returns NetBox URL. Necessary for payload generation.
    pub fn get_netbox_uri(&self) -> &str {
        &self.netbox.netbox_uri
    }

    /// Returns API auth token. Necessary for payload generation.
    pub fn get_api_token(&self) -> &str {
        &self.netbox.netbox_api_token
    }
}