use std::{fs, path::PathBuf};

use anyhow::{bail, Context};
use serde::Deserialize;

#[derive(Deserialize, Clone)]
pub struct ControlConfig {
    pub secret: String,
    pub burst_command: String,
    pub cutdown_command: String,
}

#[derive(Deserialize, Clone)]
pub struct Config {
    pub paths: Vec<PathBuf>,
    pub callsign: String,

    pub control: Option<ControlConfig>,
}

impl Config {
    pub fn load() -> anyhow::Result<Self> {
        let file_contents = read_conf_file()?;
        let config = toml::from_str(&file_contents).context("parsing config file")?;

        Ok(config)
    }
}

fn read_conf_file() -> anyhow::Result<String> {
    let filenames = ["config.toml", "/etc/balloon_tx/config.toml"];
    for filename in filenames.iter() {
        if let Ok(x) = fs::read_to_string(filename) {
            return Ok(x);
        }
    }

    bail!("Could not open config file. Should either be `config.toml` in the current directory, or in /etc/balloon_tx/")
}