summaryrefslogtreecommitdiffstats
path: root/pkgs/by-name/fu/fupdate-sys2/src/main.rs
blob: d2dd19f3229f0e31ff51cf07069fe4889d21bb37 (plain) (blame)
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
// nixos-config - My current NixOS configuration
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of my nixos-config.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::{
    ops::Deref,
    process::{Command, Stdio},
    thread,
};

use anyhow::{Result, bail};
use clap::{CommandFactory, Parser};
use serde_json::Value;
use tempfile::NamedTempFile;

pub mod cli;

use crate::cli::CliArgs;

macro_rules! cmd {
    ($dry_run:expr, $name:literal, $($arg:expr),*) => {{
        eprintln!("# \x1b[1;96m{}\x1b[0m {}", $name, [$($arg),*].join(" "));

        if $dry_run {
            String::new()
        } else {
        let output = Command::new($name)
            .args([
                $($arg),*
            ])
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .current_dir("/etc/nixos")
            .output()?;

        if !output.status.success() {
            bail!("`\x1b[1;96m{}\x1b[0m {}` failed.", $name, [$($arg),*].join(" "));
        }

        String::from_utf8(output.stdout)?
        }
    }};
}

fn msg(message: &'static str) {
    eprintln!("\x1b[1;96m==>\x1b[0m\x1b[1;93m {message}\x1b[0m");
}
fn msg2(message: impl Deref<Target = str>) {
    eprintln!("\x1b[1;96m ->\x1b[0m\x1b[1;93m {}\x1b[0m", &*message);
}

fn main() -> Result<(), anyhow::Error> {
    clap_complete::CompleteEnv::with_factory(CliArgs::command).complete();

    let args = CliArgs::parse();

    msg("Starting system update...");
    cmd!(args.dry_run, "git", "remote", "update", "origin", "--prune");

    if let Some(branch) = args.branch {
        cmd!(args.dry_run, "git", "switch", &branch);
        msg2(format!("Switched to branch '{branch}'"));
    }

    msg2("Updating git repository...");
    cmd!(args.dry_run, "git", "pull", "--rebase");

    let handle = thread::spawn(get_remote_default_branch);

    msg2("Updating system...");
    cmd!(
        args.dry_run,
        "nixos-rebuild",
        args.mode.to_string().as_str()
    );

    let remote_default_branch = handle.join().unwrap()?;
    cmd!(args.dry_run, "git", "switch", &remote_default_branch);
    msg2(format!("Switched to branch '{remote_default_branch}'"));

    msg("Setting oneshot boot entry to new generation..");

    let new_generation = {
        let base = cmd!(false, "bootctl", "list", "--json=short");

        let json: Value = serde_json::from_str(&base)?;

        let mut nixos_generations = vec![];
        for part in json.as_array().unwrap() {
            if part.get("sortKey").map(Value::as_str) == Some(Some("lanza")) {
                nixos_generations.push(part.get("id").unwrap().as_str().unwrap().to_owned());
            }
        }

        nixos_generations.first().unwrap().to_owned()
    };

    let last_used_variable_name = {
        let mut name = None;
        let all = cmd!(false, "efivar", "--list");

        for line in all.trim().lines() {
            if line.contains("LoaderEntryLastBooted") {
                name = Some(line.to_owned());
            }
        }

        name.unwrap()
    };
    let data_file = {
        use std::io::Write;

        let mut named = NamedTempFile::new()?;

        let mut data = Vec::with_capacity(new_generation.len() * 2);
        for ch in new_generation.chars() {
            data.push(ch as u8);
            data.push(b'\0');
        }

        data.push(b'\0');
        data.push(b'\0');

        named.write_all(data.as_slice())?;

        let str = cmd!(
            false,
            "hexdump",
            "-C",
            named.path().as_os_str().to_str().unwrap()
        );
        eprintln!("{str}");

        named
    };
    cmd!(
        args.dry_run,
        "efivar",
        "--name",
        &last_used_variable_name,
        "--write",
        "--datafile",
        data_file.path().as_os_str().to_str().unwrap()
    );

    data_file.close()?;

    msg("Finished Update!");

    Ok(())
}

fn get_remote_default_branch() -> Result<String> {
    let mut final_output = None;

    let output = cmd!(false, "git", "remote", "show", "origin");
    for line in output.trim().lines() {
        if line.contains("HEAD") {
            let base = line.split(':').skip(1).take(1).last().unwrap();
            let base = base.replacen(" *", "", 1);
            let base = base
                .chars()
                .rev()
                .collect::<String>()
                .replacen(" *", "", 1)
                .chars()
                .rev()
                .collect::<String>()
                .trim()
                .to_owned();

            final_output = Some(base);
        }
    }

    Ok(final_output.unwrap())
}

#[cfg(test)]
mod test {
    use clap::CommandFactory;

    #[test]
    fn verify_cli() {
        super::CliArgs::command().debug_assert();
    }
}