| 1 | |
| 2 | |
| 3 | |
| 4 | use crate::Res; |
| 5 | use crate::config; |
| 6 | use crate::install::{file_sha256, systemctl}; |
| 7 | use std::env; |
| 8 | use std::fs::{self, DirBuilder, File, OpenOptions, Permissions}; |
| 9 | use std::io::{self, Write}; |
| 10 | use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; |
| 11 | use std::path::Path; |
| 12 | |
| 13 | |
| 14 | const CONFIG_TEMPLATE: &str = r##"# kur config, written by `kur setup`. Field reference: README.md. |
| 15 | # Paths may start with ~/, which expands to $HOME/. This file is mode 0600: keep it that way. |
| 16 | |
| 17 | # Forge base URL. A trailing slash is fine. |
| 18 | forge = "https://git.tahinli.com" |
| 19 | |
| 20 | # Optional: file holding a forge token for private repos. Read once at start, trimmed. |
| 21 | # Use a read-only token. Must be mode 0600. |
| 22 | # token_file = "~/.config/kur/token" |
| 23 | |
| 24 | # kur updates itself. There is no unit: the new binary is swapped in and used from the next |
| 25 | # timer run on. kur runs `kur --version` on the new build before swapping it in, so a broken |
| 26 | # build is never installed. |
| 27 | [[app]] |
| 28 | name = "kur" |
| 29 | repo = "Tahinli/kur" |
| 30 | asset = "kur-{arch}-linux" |
| 31 | path = "~/bin/kur" |
| 32 | check = ["--version"] |
| 33 | |
| 34 | # Uncomment once im runs as a user unit of this account and has a v* release. |
| 35 | # [[app]] |
| 36 | # name = "im" |
| 37 | # repo = "Tahinli/im" |
| 38 | # asset = "im-{arch}-linux" |
| 39 | # path = "~/bin/im" |
| 40 | # unit = "im.service" |
| 41 | # health_url = "http://127.0.0.1:7650/healthz" |
| 42 | "##; |
| 43 | |
| 44 | const KUR_SERVICE: &str = include_str!("../deploy/user/kur.service"); |
| 45 | const KUR_TIMER: &str = include_str!("../deploy/user/kur.timer"); |
| 46 | |
| 47 | const ROOT_MSG: &str = "run kur as the account that runs the apps, not as root"; |
| 48 | const SYSTEMCTL_MSG: &str = "systemctl --user failed; kur needs a login session of this account (for example: sudo machinectl shell <user>@)"; |
| 49 | |
| 50 | |
| 51 | pub fn run(config_path: &Path) -> Res<()> { |
| 52 | refuse_root()?; |
| 53 | let home = config::home_dir().ok_or("HOME is not set")?; |
| 54 | install_binary(&home)?; |
| 55 | write_config(config_path)?; |
| 56 | write_units(&config::config_base()?.join("systemd").join("user"))?; |
| 57 | enable_timer()?; |
| 58 | println!("kur: setup: config file {}", config_path.display()); |
| 59 | println!("kur: setup: done; kur checks for updates every 5 minutes (journalctl --user -u kur)"); |
| 60 | Ok(()) |
| 61 | } |
| 62 | |
| 63 | |
| 64 | fn refuse_root() -> Res<()> { |
| 65 | let uid = fs::metadata("/proc/self") |
| 66 | .map_err(|e| format!("cannot read /proc/self: {e}"))? |
| 67 | .uid(); |
| 68 | if uid == 0 { |
| 69 | return Err(ROOT_MSG.into()); |
| 70 | } |
| 71 | Ok(()) |
| 72 | } |
| 73 | |
| 74 | |
| 75 | fn install_binary(home: &Path) -> Res<()> { |
| 76 | let source = |
| 77 | env::current_exe().map_err(|e| format!("cannot find the running kur binary: {e}"))?; |
| 78 | let bin_dir = home.join("bin"); |
| 79 | let target = bin_dir.join("kur"); |
| 80 | let display = target.display(); |
| 81 | |
| 82 | let same_file = matches!( |
| 83 | (fs::canonicalize(&source), fs::canonicalize(&target)), |
| 84 | (Ok(a), Ok(b)) if a == b |
| 85 | ); |
| 86 | if same_file { |
| 87 | println!("kur: setup: binary already in place ({display})"); |
| 88 | return Ok(()); |
| 89 | } |
| 90 | let source_sha = file_sha256(&source)?.ok_or("cannot read the running kur binary")?; |
| 91 | if file_sha256(&target)?.as_deref() == Some(source_sha.as_str()) { |
| 92 | println!("kur: setup: binary already in place ({display})"); |
| 93 | return Ok(()); |
| 94 | } |
| 95 | |
| 96 | if !bin_dir.is_dir() { |
| 97 | DirBuilder::new() |
| 98 | .mode(0o755) |
| 99 | .create(&bin_dir) |
| 100 | .and_then(|()| fs::set_permissions(&bin_dir, Permissions::from_mode(0o755))) |
| 101 | .map_err(|e| format!("create {}: {e}", bin_dir.display()))?; |
| 102 | } |
| 103 | let bytes = fs::read(&source).map_err(|e| format!("read {}: {e}", source.display()))?; |
| 104 | write_atomic(&target, &bytes, 0o755).map_err(|e| format!("install {display}: {e}"))?; |
| 105 | println!("kur: setup: installed binary to {display}"); |
| 106 | Ok(()) |
| 107 | } |
| 108 | |
| 109 | |
| 110 | fn write_config(path: &Path) -> Res<()> { |
| 111 | let display = path.display(); |
| 112 | if path |
| 113 | .try_exists() |
| 114 | .map_err(|e| format!("cannot check {display}: {e}"))? |
| 115 | { |
| 116 | println!("kur: setup: config already in place ({display})"); |
| 117 | return Ok(()); |
| 118 | } |
| 119 | if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) { |
| 120 | DirBuilder::new() |
| 121 | .recursive(true) |
| 122 | .mode(0o700) |
| 123 | .create(dir) |
| 124 | .map_err(|e| format!("create {}: {e}", dir.display()))?; |
| 125 | } |
| 126 | |
| 127 | let result = OpenOptions::new() |
| 128 | .write(true) |
| 129 | .create_new(true) |
| 130 | .mode(0o600) |
| 131 | .open(path) |
| 132 | .and_then(|mut file| { |
| 133 | file.write_all(CONFIG_TEMPLATE.as_bytes())?; |
| 134 | file.sync_all() |
| 135 | }); |
| 136 | result.map_err(|e| format!("write config {display}: {e}"))?; |
| 137 | println!("kur: setup: wrote starter config {display}"); |
| 138 | Ok(()) |
| 139 | } |
| 140 | |
| 141 | |
| 142 | fn write_units(dir: &Path) -> Res<()> { |
| 143 | DirBuilder::new() |
| 144 | .recursive(true) |
| 145 | .mode(0o755) |
| 146 | .create(dir) |
| 147 | .map_err(|e| format!("create {}: {e}", dir.display()))?; |
| 148 | let mut changed = false; |
| 149 | for (name, content) in [("kur.service", KUR_SERVICE), ("kur.timer", KUR_TIMER)] { |
| 150 | let path = dir.join(name); |
| 151 | if fs::read_to_string(&path).ok().as_deref() == Some(content) { |
| 152 | continue; |
| 153 | } |
| 154 | write_atomic(&path, content.as_bytes(), 0o644) |
| 155 | .map_err(|e| format!("write {}: {e}", path.display()))?; |
| 156 | changed = true; |
| 157 | } |
| 158 | if changed { |
| 159 | println!("kur: setup: wrote user units to {}", dir.display()); |
| 160 | } else { |
| 161 | println!( |
| 162 | "kur: setup: user units already in place ({})", |
| 163 | dir.display() |
| 164 | ); |
| 165 | } |
| 166 | Ok(()) |
| 167 | } |
| 168 | |
| 169 | |
| 170 | fn enable_timer() -> Res<()> { |
| 171 | |
| 172 | if env::var_os("XDG_RUNTIME_DIR").is_none_or(|value| value.is_empty()) { |
| 173 | return Err(SYSTEMCTL_MSG.into()); |
| 174 | } |
| 175 | systemctl(&["daemon-reload"]).map_err(|_| SYSTEMCTL_MSG.to_string())?; |
| 176 | systemctl(&["enable", "--now", "kur.timer"]).map_err(|_| SYSTEMCTL_MSG.to_string())?; |
| 177 | println!("kur: setup: kur.timer enabled and started"); |
| 178 | Ok(()) |
| 179 | } |
| 180 | |
| 181 | |
| 182 | fn write_atomic(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { |
| 183 | let mut name = path.file_name().unwrap_or_default().to_os_string(); |
| 184 | name.push(".kur-new"); |
| 185 | let tmp = path.with_file_name(name); |
| 186 | let _ = fs::remove_file(&tmp); |
| 187 | let result = write_tmp_and_rename(&tmp, path, bytes, mode); |
| 188 | if result.is_err() { |
| 189 | let _ = fs::remove_file(&tmp); |
| 190 | } |
| 191 | result |
| 192 | } |
| 193 | |
| 194 | fn write_tmp_and_rename(tmp: &Path, path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { |
| 195 | let mut file = OpenOptions::new() |
| 196 | .write(true) |
| 197 | .create_new(true) |
| 198 | .mode(mode) |
| 199 | .open(tmp)?; |
| 200 | file.write_all(bytes)?; |
| 201 | file.set_permissions(Permissions::from_mode(mode))?; |
| 202 | file.sync_all()?; |
| 203 | drop(file); |
| 204 | fs::rename(tmp, path)?; |
| 205 | let parent = match path.parent() { |
| 206 | Some(dir) if !dir.as_os_str().is_empty() => dir, |
| 207 | _ => Path::new("."), |
| 208 | }; |
| 209 | File::open(parent)?.sync_all() |
| 210 | } |