Kur sets itself up on first run (or with kur setup): copies itself to ~/bin, writes a starter config, installs and starts the user timer
Browse files at this commit286a6e76e526b6cb81f8284fd6f684731f11ee61Parent: 4725f2bAll checks have passed
Show checks
ci/buildSucceededDetails
- feat
- kur sets itself up on first run (or with kur setup): copies itself to ~/bin, writes a starter config, installs and starts the user timer
- refuses root
6 changed files +286 -37
- README.md +30 -22
- deploy/user/kur.service +0 -1
- src/config.rs +12 -10
- src/install.rs +2 -2
- src/main.rs +32 -2
- src/setup.rs +210 -0
README.mdmodified+30 -22
| @@ -41,38 +41,41 @@ file. To retry a build, delete its line, or delete the file to clear the list fo | |||
| 41 | 41 | ||
| 42 | ## Install | 42 | ## Install |
| 43 | 43 | ||
| 44 | -kur and the apps it installs run as one unprivileged account, for example `apps`. Root is needed once, | 44 | +kur and the apps it installs run as one unprivileged account, for example `apps`. Do not run kur as |
| 45 | -to create the account and enable lingering. Everything after that is done as the account. | 45 | +root. Get a working user session for the account first. Plain `sudo -u apps` does not work, because it |
| 46 | - | 46 | +has no `XDG_RUNTIME_DIR` and `systemctl --user` fails there. Use `machinectl`: |
| 47 | -As root, once: | ||
| 48 | 47 | ||
| 49 | ```sh | 48 | ```sh |
| 50 | -useradd -m apps # any name works; the examples use apps | 49 | +sudo machinectl shell apps@ |
| 51 | -loginctl enable-linger apps # keeps the account's user manager running without a login | ||
| 52 | ``` | 50 | ``` |
| 53 | 51 | ||
| 54 | -Then get a working user session for the account. Plain `sudo -u apps` does not work for this: it has | 52 | +As that account, in the directory with the release file for this machine (`kur-x86_64-linux`, or |
| 55 | -no `XDG_RUNTIME_DIR`, so `systemctl --user` fails there. Use `machinectl` instead: | 53 | +`kur-aarch64-linux` on aarch64 hosts): |
| 56 | 54 | ||
| 57 | ```sh | 55 | ```sh |
| 58 | -sudo machinectl shell apps@ | 56 | +sha256sum -c SHA256SUMS # verify the download; add --ignore-missing if you fetched one binary only |
| 57 | +chmod +x kur-x86_64-linux | ||
| 58 | +./kur-x86_64-linux # first run: sets kur up | ||
| 59 | ``` | 59 | ``` |
| 60 | 60 | ||
| 61 | -As that user, from a checkout of this repo (or with the files copied over), with the kur release binary | 61 | +With no command, kur runs setup when the config file is missing, and otherwise behaves like |
| 62 | -for this machine in the current directory: | 62 | +`kur status`. Setup is idempotent and does this, printing one line per step: |
| 63 | 63 | ||
| 64 | -```sh | 64 | +1. Refuses to run as root. |
| 65 | -install -d ~/bin ~/.config/kur ~/.config/systemd/user | 65 | +2. Copies the binary to `~/bin/kur` (skipped if the same file is already there). |
| 66 | -install -m 0755 kur-x86_64-linux ~/bin/kur # aarch64 hosts use kur-aarch64-linux | 66 | +3. Writes a starter config to `~/.config/kur/kur.toml` (mode 0600). It contains kur itself as an app. |
| 67 | -install -m 0600 config/kur.example.toml ~/.config/kur/kur.toml # then edit it | 67 | + An existing config is never touched. |
| 68 | -# Optional, for private repos. Use a read-only token. | 68 | +4. Writes `kur.service` and `kur.timer` to `~/.config/systemd/user/` (only if missing or different). |
| 69 | -(umask 077; printf '%s\n' 'TOKEN' > ~/.config/kur/token) | 69 | +5. Runs `systemctl --user daemon-reload` and `systemctl --user enable --now kur.timer`. |
| 70 | -install -m 0644 deploy/user/kur.service deploy/user/kur.timer ~/.config/systemd/user/ | 70 | +6. Prints the config path and the done line. |
| 71 | -systemctl --user daemon-reload | ||
| 72 | -systemctl --user enable --now kur.timer | ||
| 73 | -``` | ||
| 74 | 71 | ||
| 75 | -The config file must be mode 0600. If `token_file` is set, the token file must be mode 0600 too. | 72 | +Then add your apps to the config. Each one needs a `[[app]]` table (see the reference below). The |
| 73 | +config file must be mode 0600. If `token_file` is set, the token file must be mode 0600 too. For | ||
| 74 | +private repos, put a read-only forge token in `~/.config/kur/token` with mode 0600, and set | ||
| 75 | +`token_file = "~/.config/kur/token"` in the config. | ||
| 76 | + | ||
| 77 | +`kur setup` runs setup explicitly. Use it to repair or reinstall: it puts back any missing binary, | ||
| 78 | +config or unit, and it changes nothing that is already in place. | ||
| 76 | 79 | ||
| 77 | Each app must be a user unit of the same account. Its binary lives under `~/bin`, and its unit goes in | 80 | Each app must be a user unit of the same account. Its binary lives under `~/bin`, and its unit goes in |
| 78 | `~/.config/systemd/user/`. The app units are not part of this repo. For example, im's unit is | 81 | `~/.config/systemd/user/`. The app units are not part of this repo. For example, im's unit is |
| @@ -104,6 +107,8 @@ journalctl _SYSTEMD_USER_UNIT=kur.service | |||
| 104 | ## Commands | 107 | ## Commands |
| 105 | 108 | ||
| 106 | ``` | 109 | ``` |
| 110 | +kur first run: sets up if the config file is missing, else same as status | ||
| 111 | +kur setup set up kur (idempotent); see Install | ||
| 107 | kur run process every app once | 112 | kur run process every app once |
| 108 | kur run <name> process one app | 113 | kur run <name> process one app |
| 109 | kur status show installed and newest versions; changes nothing | 114 | kur status show installed and newest versions; changes nothing |
| @@ -111,6 +116,9 @@ kur --version print "kur <version>" | |||
| 111 | kur help print usage (also used for unknown commands, exit 2) | 116 | kur help print usage (also used for unknown commands, exit 2) |
| 112 | ``` | 117 | ``` |
| 113 | 118 | ||
| 119 | +A bare `kur` runs setup when the config file does not exist, and otherwise does the same as | ||
| 120 | +`kur status`. `kur run` and `kur status` never run setup. | ||
| 121 | + | ||
| 114 | Global option: `--config <path>`, placed before the command. Otherwise `KUR_CONFIG` is used, then | 122 | Global option: `--config <path>`, placed before the command. Otherwise `KUR_CONFIG` is used, then |
| 115 | `$XDG_CONFIG_HOME/kur/kur.toml`, or `~/.config/kur/kur.toml` when `XDG_CONFIG_HOME` is not set. Empty | 123 | `$XDG_CONFIG_HOME/kur/kur.toml`, or `~/.config/kur/kur.toml` when `XDG_CONFIG_HOME` is not set. Empty |
| 116 | environment variables count as unset. If neither `XDG_CONFIG_HOME` nor `HOME` is set, kur prints an | 124 | environment variables count as unset. If neither `XDG_CONFIG_HOME` nor `HOME` is set, kur prints an |
deploy/user/kur.servicemodified+0 -1
| @@ -3,7 +3,6 @@ Description=kur: install newest forge releases of configured apps | |||
| 3 | 3 | ||
| 4 | [Service] | 4 | [Service] |
| 5 | # User unit for the shared app account (for example "apps"). It runs as that account, never as root. | 5 | # User unit for the shared app account (for example "apps"). It runs as that account, never as root. |
| 6 | -# The account needs `loginctl enable-linger <account>` so the timer runs without a login session. | ||
| 7 | # The config is read from the default path, ~/.config/kur/kur.toml (or $XDG_CONFIG_HOME). | 6 | # The config is read from the default path, ~/.config/kur/kur.toml (or $XDG_CONFIG_HOME). |
| 8 | Type=oneshot | 7 | Type=oneshot |
| 9 | ExecStart=%h/bin/kur run | 8 | ExecStart=%h/bin/kur run |
src/config.rsmodified+12 -10
| @@ -89,7 +89,7 @@ fn env_value(name: &str) -> Option<OsString> { | |||
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | /// `$HOME`, if set and not empty. | 91 | /// `$HOME`, if set and not empty. |
| 92 | -fn home_dir() -> Option<PathBuf> { | 92 | +pub(crate) fn home_dir() -> Option<PathBuf> { |
| 93 | env_value("HOME").map(PathBuf::from) | 93 | env_value("HOME").map(PathBuf::from) |
| 94 | } | 94 | } |
| 95 | 95 | ||
| @@ -104,15 +104,17 @@ pub fn config_path(cli: Option<PathBuf>) -> Res<PathBuf> { | |||
| 104 | /// Config file used when neither `--config` nor `KUR_CONFIG` is set: | 104 | /// Config file used when neither `--config` nor `KUR_CONFIG` is set: |
| 105 | /// `$XDG_CONFIG_HOME/kur/kur.toml`, else `$HOME/.config/kur/kur.toml`. | 105 | /// `$XDG_CONFIG_HOME/kur/kur.toml`, else `$HOME/.config/kur/kur.toml`. |
| 106 | pub fn default_path() -> Res<PathBuf> { | 106 | pub fn default_path() -> Res<PathBuf> { |
| 107 | - let base = match env_value("XDG_CONFIG_HOME") { | 107 | + Ok(config_base()?.join("kur").join("kur.toml")) |
| 108 | - Some(dir) => PathBuf::from(dir), | 108 | +} |
| 109 | - None => home_dir() | 109 | + |
| 110 | - .ok_or_else(|| { | 110 | +/// `$XDG_CONFIG_HOME`, else `$HOME/.config`. Base for kur's config and the systemd user units. |
| 111 | - "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string() | 111 | +pub(crate) fn config_base() -> Res<PathBuf> { |
| 112 | - })? | 112 | + match env_value("XDG_CONFIG_HOME") { |
| 113 | - .join(".config"), | 113 | + Some(dir) => Ok(PathBuf::from(dir)), |
| 114 | - }; | 114 | + None => home_dir().map(|home| home.join(".config")).ok_or_else(|| { |
| 115 | - Ok(base.join("kur").join("kur.toml")) | 115 | + "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string() |
| 116 | + }), | ||
| 117 | + } | ||
| 116 | } | 118 | } |
| 117 | 119 | ||
| 118 | /// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`. | 120 | /// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`. |
src/install.rsmodified+2 -2
| @@ -105,7 +105,7 @@ fn short(sha: &str) -> &str { | |||
| 105 | } | 105 | } |
| 106 | 106 | ||
| 107 | /// Lowercase hex sha256 of the file at `path`, or None if it does not exist. | 107 | /// Lowercase hex sha256 of the file at `path`, or None if it does not exist. |
| 108 | -fn file_sha256(path: &Path) -> Res<Option<String>> { | 108 | +pub(crate) fn file_sha256(path: &Path) -> Res<Option<String>> { |
| 109 | let mut file = match File::open(path) { | 109 | let mut file = match File::open(path) { |
| 110 | Ok(file) => file, | 110 | Ok(file) => file, |
| 111 | Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None), | 111 | Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None), |
| @@ -253,7 +253,7 @@ fn is_active(unit: &str) -> bool { | |||
| 253 | } | 253 | } |
| 254 | 254 | ||
| 255 | /// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used. | 255 | /// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used. |
| 256 | -fn systemctl(args: &[&str]) -> Result<(), String> { | 256 | +pub(crate) fn systemctl(args: &[&str]) -> Result<(), String> { |
| 257 | let status = Command::new("systemctl") | 257 | let status = Command::new("systemctl") |
| 258 | .arg("--user") | 258 | .arg("--user") |
| 259 | .args(args) | 259 | .args(args) |
src/main.rsmodified+32 -2
| @@ -6,21 +6,24 @@ mod config; | |||
| 6 | mod forge; | 6 | mod forge; |
| 7 | mod install; | 7 | mod install; |
| 8 | mod migrate; | 8 | mod migrate; |
| 9 | +mod setup; | ||
| 9 | 10 | ||
| 10 | use crate::config::{App, Config}; | 11 | use crate::config::{App, Config}; |
| 11 | use crate::forge::Forge; | 12 | use crate::forge::Forge; |
| 12 | use std::env; | 13 | use std::env; |
| 13 | -use std::path::PathBuf; | 14 | +use std::path::{Path, PathBuf}; |
| 14 | use std::process::ExitCode; | 15 | use std::process::ExitCode; |
| 15 | 16 | ||
| 16 | /// Crate-wide result type; errors are human-readable messages. | 17 | /// Crate-wide result type; errors are human-readable messages. |
| 17 | pub type Res<T> = Result<T, String>; | 18 | pub type Res<T> = Result<T, String>; |
| 18 | 19 | ||
| 19 | -const USAGE: &str = "usage: kur [--config <path>] <command> | 20 | +const USAGE: &str = "usage: kur [--config <path>] [command] |
| 20 | 21 | ||
| 21 | commands: | 22 | commands: |
| 23 | + (none) first run: set up if the config file is missing, else the same as status | ||
| 22 | run [app] install newer releases (all apps, or only <app>) | 24 | run [app] install newer releases (all apps, or only <app>) |
| 23 | status show installed and newest releases; changes nothing | 25 | status show installed and newest releases; changes nothing |
| 26 | + setup set up kur (idempotent): install the binary, write the config, install the timer | ||
| 24 | --version print the version | 27 | --version print the version |
| 25 | "; | 28 | "; |
| 26 | 29 | ||
| @@ -43,9 +46,24 @@ fn main() -> ExitCode { | |||
| 43 | } | 46 | } |
| 44 | let words: Vec<&str> = words.iter().map(String::as_str).collect(); | 47 | let words: Vec<&str> = words.iter().map(String::as_str).collect(); |
| 45 | let (only, status) = match words.as_slice() { | 48 | let (only, status) = match words.as_slice() { |
| 49 | + ["setup"] => return setup_command(cli_config.as_deref()), | ||
| 46 | ["run"] => (None, false), | 50 | ["run"] => (None, false), |
| 47 | ["run", name] => (Some(*name), false), | 51 | ["run", name] => (Some(*name), false), |
| 48 | ["status"] => (None, true), | 52 | ["status"] => (None, true), |
| 53 | + [] => match config::config_path(cli_config.clone()) { | ||
| 54 | + Ok(path) => match path.try_exists() { | ||
| 55 | + Ok(true) => (None, true), | ||
| 56 | + Ok(false) => return setup_command(Some(&path)), | ||
| 57 | + Err(e) => { | ||
| 58 | + eprintln!("kur: cannot check {}: {e}", path.display()); | ||
| 59 | + return ExitCode::FAILURE; | ||
| 60 | + } | ||
| 61 | + }, | ||
| 62 | + Err(e) => { | ||
| 63 | + eprintln!("kur: {e}"); | ||
| 64 | + return ExitCode::FAILURE; | ||
| 65 | + } | ||
| 66 | + }, | ||
| 49 | _ => return usage(), | 67 | _ => return usage(), |
| 50 | }; | 68 | }; |
| 51 | 69 | ||
| @@ -125,6 +143,18 @@ fn process_apps(cfg: &Config, apps: &[&App], status: bool) -> ExitCode { | |||
| 125 | } | 143 | } |
| 126 | } | 144 | } |
| 127 | 145 | ||
| 146 | +/// Runs first-run setup for the resolved config path (`cli` overrides it, as `--config` does). | ||
| 147 | +fn setup_command(cli: Option<&Path>) -> ExitCode { | ||
| 148 | + let result = config::config_path(cli.map(Path::to_path_buf)).and_then(|path| setup::run(&path)); | ||
| 149 | + match result { | ||
| 150 | + Ok(()) => ExitCode::SUCCESS, | ||
| 151 | + Err(e) => { | ||
| 152 | + eprintln!("kur: setup: {e}"); | ||
| 153 | + ExitCode::FAILURE | ||
| 154 | + } | ||
| 155 | + } | ||
| 156 | +} | ||
| 157 | + | ||
| 128 | /// Prints usage and returns exit code 2 (bad invocation). | 158 | /// Prints usage and returns exit code 2 (bad invocation). |
| 129 | fn usage() -> ExitCode { | 159 | fn usage() -> ExitCode { |
| 130 | eprint!("{USAGE}"); | 160 | eprint!("{USAGE}"); |
src/setup.rsadded+210 -0
| @@ -0,0 +1,210 @@ | |||
| 1 | +//! First-run setup, run by `kur setup` and by a bare `kur` when the config file is missing. | ||
| 2 | +//! Each step is idempotent, so running it again repairs or reinstalls whatever is missing. | ||
| 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 | +/// Starter config. Must parse with `config::load`; the commented-out entry must stay fully commented. | ||
| 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 | +/// Runs every setup step in order and stops at the first error. | ||
| 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 | +/// Step 1: refuses to run as root. | ||
| 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 | +/// Step 2: copies the running binary to `$HOME/bin/kur` unless the target already matches. | ||
| 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 | +/// Step 3: writes the starter config if the file does not exist. An existing file is never touched. | ||
| 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 | + // Mode 0600 from creation, so the file is never readable by others. | ||
| 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 | +/// Step 4: writes the embedded user units into `dir`, only where missing or different. | ||
| 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 | +/// Step 5: reloads the user manager and enables the timer. Needs a login session of this account. | ||
| 170 | +fn enable_timer() -> Res<()> { | ||
| 171 | + // Without XDG_RUNTIME_DIR there is no user manager to talk to, so fail before calling systemctl. | ||
| 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 | +/// Writes `bytes` to a temp file next to `path` with `mode`, fsyncs it, then renames it over `path`. | ||
| 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 | +} | ||