summaryrefslogtreecommitdiff
path: root/src/tasks.rs
blob: 9175214a8eb9af30f34671284629a3a4ed317300 (plain)
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
pub struct Task<'a> {
    pub name: &'a str,
    pub exec: fn(&[&str]) -> Result<String, String>,
}

impl<'a> PartialEq for &'a Task<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

pub const TASKS: &[Task<'static>] = &[Task { name: "nop", exec: no_op }, Task { name: "exec", exec: exec }, NETWORK_T];

pub const NETWORK_T: Task<'static> = Task { name: "network", exec: network };

fn no_op(_: &[&str]) -> Result<String, String> {
    Ok("".to_string())
}

fn exec(cmds: &[&str]) -> Result<String, String> {
    use std::process::Command;
    // TODO: fmt and add exit code, and add support for both stdout and stderr, and
    // support for no output
    match Command::new(cmds[0]).args(&cmds[1..]).output() {
        Ok(o) => {
            if o.status.success() {
                Ok(String::from_utf8_lossy(&o.stdout).to_string())
            } else {
                Err(String::from_utf8_lossy(&o.stderr).to_string())
            }
        }
        Err(e) => Err(e.to_string()),
    }
}

fn network(switch: &[&str]) -> Result<String, String> {
    use std::process::{Command, Stdio};
    let switch: bool = switch[0].parse::<bool>().map_err(|e| e.to_string())?;

    // TODO: windows and linux

    // todo let .. = Command::new('networksetup')
    #[cfg(target_os = "macos")]
    {
        use std::io::Read;
        match Command::new("networksetup").arg("-listallhardwareports").stdout(Stdio::piped()).spawn() {
            Ok(devs) => {
                match Command::new("awk")
                    .arg(r#"/Wi-Fi|AirPort/{getline; print $2}"#)
                    .stdin(Stdio::from(match devs.stdout {
                        Some(s) => s,
                        None => match devs.stderr {
                            Some(mut e) => {
                                let mut reason = String::new();
                                if let Err(e) = e.read_to_string(&mut reason) {
                                    return Err(format!("networksetup failed to list hardware: {e}"));
                                }
                                return Err(format!("networksetup failed to list hardware: {reason}"));
                            }
                            None => Err("networksetup failed to list hardware".to_string())?,
                        },
                    }))
                    .stdout(Stdio::piped())
                    .spawn()
                {
                    Ok(dev) => match Command::new("networksetup")
                        .arg("-setairportpower")
                        .arg(match dev.stdout {
                            Some(mut o) => {
                                let mut output = String::new();
                                if let Err(e) = o.read_to_string(&mut output) {
                                    return Err(format!("awk failed to get device from networksetup list hardware: {e}"));
                                };
                                output
                            }
                            None => match dev.stderr {
                                Some(mut e) => {
                                    let mut reason = String::new();
                                    if let Err(e) = e.read_to_string(&mut reason) {
                                        return Err(format!("awk failed to get device from networksetup list hardware: {e}"));
                                    }
                                    return Err(format!("awk failed to get device from networksetup list hardware: {reason}"));
                                }
                                None => Err("awk failed to get device from networksetup list hardware".to_string())?,
                            },
                        })
                        .arg(if switch { "on" } else { "off" })
                        .output()
                    {
                        Ok(o) => {
                            if o.status.success() {
                                Ok(String::from_utf8_lossy(&o.stdout).to_string())
                            } else {
                                Err(String::from_utf8_lossy(&o.stderr).to_string())
                            }
                        }
                        Err(e) => Err(e.to_string()),
                    },
                    Err(e) => Err(e.to_string()),
                }
            }
            Err(e) => Err(e.to_string()),
        }
    }

    #[cfg(not(target_os = "macos"))]
    Err("not implemented".to_string())
}

#[derive(Debug)]
pub enum IntoTaskErr {
    NotFound(String),
}

impl TryFrom<&str> for &'static Task<'static> {
    type Error = IntoTaskErr;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        for task in TASKS {
            if task.name == value {
                return Ok(task);
            }
        }
        Err(IntoTaskErr::NotFound(value.to_string()))
    }
}