hazine 0.2.6

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! `hazine setup`: install hazine and DuckDB on a Linux host with systemd,
//! and configure them for a DuckLake catalog in a remote Postgres and data in
//! S3-compatible object storage.
//!
//! Setup is idempotent: rerun it to change settings. Files it manages are
//! rewritten (an existing, different version is kept as `<file>.bak`), and
//! secrets already in `/etc/hazine/hazine.env` are kept unless new ones are
//! given.

pub mod render;

use std::collections::HashMap;
use std::io::{BufRead, IsTerminal, Write};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

pub use render::{Catalog, Resources, Secrets, SslMode, Storage, UrlStyle};

use crate::tempdir::TempDir;
use crate::{Error, token};

/// The service account DuckDB runs as.
pub const USER: &str = "hazine";
/// The service account's home: extensions, temp files.
pub const HOME: &str = "/var/lib/hazine";
/// Configuration.
pub const ETC: &str = "/etc/hazine";
/// Where hazine is installed.
pub const HAZINE_BIN: &str = "/usr/local/bin/hazine";
/// Where the DuckDB CLI is installed.
pub const DUCKDB_BIN: &str = "/usr/local/bin/duckdb";
/// The systemd unit.
pub const UNIT: &str = "/etc/systemd/system/hazine.service";

/// The extensions `init.sql` loads.
const EXTENSIONS: &str = "INSTALL quack; INSTALL ducklake; INSTALL postgres; INSTALL httpfs;";

/// What `hazine setup` was asked to do.
#[derive(Debug, Clone)]
pub struct Options {
    pub catalog: Catalog,
    pub storage: Storage,
    /// Secrets given now; missing ones come from the existing env file, or a
    /// prompt.
    pub pg_password: Option<String>,
    pub s3_key_id: Option<String>,
    pub s3_secret: Option<String>,
    /// The DuckDB release to install, e.g. `2.0.1`.
    pub duckdb_version: String,
    pub quack_addr: SocketAddr,
    /// Overrides for what is derived from the host's CPUs and memory.
    pub threads: Option<usize>,
    pub memory_limit: Option<String>,
    pub memory_max: Option<String>,
    /// Enable and (re)start the service at the end.
    pub start: bool,
    /// Show what would be done; change nothing.
    pub dry_run: bool,
}

/// Run setup. Must run as root, except with `dry_run`.
pub fn run(options: Options) -> Result<(), Error> {
    if !options.quack_addr.ip().is_loopback() {
        return Err(Error::NotLoopback {
            addr: options.quack_addr,
        });
    }
    if !options.dry_run {
        if !cfg!(target_os = "linux") {
            return Err(Error::Unsupported("hazine setup needs Linux with systemd"));
        }
        if effective_uid()? != 0 {
            return Err(Error::NotRoot);
        }
    }
    let resources = resources(&options)?;
    let env_path = Path::new(ETC).join("hazine.env");
    let secrets = secrets(&options, &env_path)?;
    let init_sql = render::init_sql(&options.storage, &resources);
    let env_file = render::env_file(
        &secrets,
        &options.catalog,
        &options.storage,
        options.quack_addr,
    )?;
    let unit_file = render::unit_file(&resources);

    if options.dry_run {
        let redacted = render::env_file(
            &Secrets {
                quack_token: "[REDACTED]".into(),
                pg_password: "[REDACTED]".into(),
                s3_key_id: "[REDACTED]".into(),
                s3_secret: "[REDACTED]".into(),
            },
            &options.catalog,
            &options.storage,
            options.quack_addr,
        )?;
        print_plan(
            &options,
            &[
                (Path::new(ETC).join("init.sql"), init_sql),
                (env_path, redacted),
                (PathBuf::from(UNIT), unit_file),
            ],
        );
        return Ok(());
    }

    // Whether anything the running service uses changed, so it needs a restart.
    let mut changed = install_self()?;
    changed |= install_duckdb(&options.duckdb_version)?;
    let account = ensure_account()?;
    install_extensions(&account)?;
    // Before writing anything: a rerun with bad settings keeps the old files.
    check_lake(&account, &options.storage, &env_file)?;

    ensure_dir(Path::new(ETC), 0o750, 0, account.gid)?;
    changed |= write_file(
        &Path::new(ETC).join("init.sql"),
        &init_sql,
        0o640,
        0,
        account.gid,
    )?;
    changed |= write_file(&env_path, &env_file, 0o640, 0, account.gid)?;
    changed |= write_file(Path::new(UNIT), &unit_file, 0o644, 0, 0)?;

    command(Command::new("systemctl").arg("daemon-reload"))?;
    if options.start {
        // Unchanged: start it if it is not running, but keep a running one
        // (and its Quack sessions).
        command(Command::new("systemctl").args(["enable", "--now", "hazine"]))?;
        if changed {
            command(Command::new("systemctl").args(["restart", "hazine"]))?;
            tracing::info!("hazine is restarting; follow it with: journalctl -u hazine -f");
        } else {
            tracing::info!("nothing changed; hazine keeps running");
        }
    } else {
        tracing::info!("set up; start with: systemctl enable --now hazine");
    }
    let port = options.quack_addr.port();
    tracing::info!(
        tunnel = %format!("ssh -N -L {port}:{} <host>", options.quack_addr),
        token = "sudo sed -n 's/^QUACK_TOKEN=//p' /etc/hazine/hazine.env",
        "connect through an SSH tunnel"
    );
    Ok(())
}

/// Threads and memory: the options, or derived from the host. With the
/// catalog and the data elsewhere, DuckDB gets most of the machine: 80% of
/// RAM, and the service is capped at 90%.
fn resources(options: &Options) -> Result<Resources, Error> {
    let threads = match options.threads {
        Some(threads) => threads,
        None => std::thread::available_parallelism()?.get(),
    };
    let (memory_limit, memory_max) = match (&options.memory_limit, &options.memory_max) {
        (Some(limit), Some(max)) => (limit.clone(), max.clone()),
        (limit, max) => {
            let total_gb = memory_gb()?;
            (
                limit
                    .clone()
                    .unwrap_or_else(|| format!("{}GB", (total_gb * 80 / 100).max(1))),
                max.clone()
                    .unwrap_or_else(|| format!("{}G", (total_gb * 90 / 100).max(1))),
            )
        }
    };
    Ok(Resources {
        threads,
        memory_limit,
        memory_max,
    })
}

/// Total memory in GiB, from `/proc/meminfo`.
pub(crate) fn memory_gb() -> Result<u64, Error> {
    let meminfo = std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::InvalidSetting {
        name: "memory",
        reason: "cannot read /proc/meminfo; give --memory-limit and --memory-max".into(),
    })?;
    parse_meminfo(&meminfo).ok_or_else(|| Error::InvalidSetting {
        name: "memory",
        reason: "no MemTotal in /proc/meminfo".into(),
    })
}

/// GiB from the `MemTotal:  131072000 kB` line.
fn parse_meminfo(meminfo: &str) -> Option<u64> {
    let kb: u64 = meminfo
        .lines()
        .find_map(|line| line.strip_prefix("MemTotal:"))?
        .split_whitespace()
        .next()?
        .parse()
        .ok()?;
    Some(kb / (1024 * 1024))
}

/// The secrets: given now, else from the existing env file, else asked for.
/// The Quack token is kept, or generated.
fn secrets(options: &Options, env_path: &Path) -> Result<Secrets, Error> {
    let existing = read_env(env_path, options.dry_run)?;
    let pick = |given: &Option<String>, name: &str, prompt: &str| -> Result<String, Error> {
        if let Some(value) = given.as_ref().filter(|v| !v.is_empty()) {
            return Ok(value.clone());
        }
        if let Some(value) = existing.get(name).filter(|v| !v.is_empty()) {
            return Ok(value.clone());
        }
        if options.dry_run {
            return Ok(String::new());
        }
        if std::io::stdin().is_terminal() {
            let value = rpassword::prompt_password(format!("{prompt}: "))?;
            if !value.is_empty() {
                return Ok(value);
            }
        }
        Err(Error::MissingSetting { name: name.into() })
    };
    let quack_token = match existing.get("QUACK_TOKEN").filter(|v| !v.is_empty()) {
        Some(token) => token.clone(),
        None => token::generate(40)?,
    };
    Ok(Secrets {
        quack_token,
        pg_password: pick(&options.pg_password, "PGPASSWORD", "Postgres password")?,
        s3_key_id: pick(&options.s3_key_id, "HAZINE_S3_KEY_ID", "S3 access key id")?,
        s3_secret: pick(
            &options.s3_secret,
            "HAZINE_S3_SECRET",
            "S3 secret access key",
        )?,
    })
}

/// The variables in the env file at `path`; none if it does not exist. In a
/// dry run, which may run without root, an unreadable file counts as none.
pub(crate) fn read_env(path: &Path, dry_run: bool) -> Result<HashMap<String, String>, Error> {
    match std::fs::read_to_string(path) {
        Ok(content) => Ok(render::parse_env(&content)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(HashMap::new()),
        Err(error) if dry_run => {
            tracing::debug!(%error, "cannot read the env file");
            Ok(HashMap::new())
        }
        Err(error) => Err(error.into()),
    }
}

/// The variables in the existing `/etc/hazine/hazine.env`, to offer earlier
/// values as defaults.
pub fn existing_env(dry_run: bool) -> Result<HashMap<String, String>, Error> {
    read_env(&Path::new(ETC).join("hazine.env"), dry_run)
}

/// A setting that was given, or else asked for on the terminal, offering
/// `existing` (from an earlier setup) as the default. Without a terminal,
/// `existing` is used if there is one. `check` validates and normalises; a
/// bad answer is asked again, a bad given value is an error.
pub fn setting(
    given: Option<String>,
    existing: Option<&str>,
    name: &str,
    prompt: &str,
    check: impl Fn(&str) -> Result<String, Error>,
) -> Result<String, Error> {
    if let Some(value) = given.filter(|v| !v.is_empty()) {
        return check(&value);
    }
    let existing = existing.filter(|v| !v.is_empty());
    if std::io::stdin().is_terminal() {
        return ask(
            &mut std::io::stdin().lock(),
            &mut std::io::stderr(),
            existing,
            prompt,
            check,
        )?
        .ok_or_else(|| Error::MissingSetting { name: name.into() });
    }
    match existing {
        Some(value) => check(value),
        None => Err(Error::MissingSetting { name: name.into() }),
    }
}

/// Ask for a value until `check` accepts it. An empty answer takes `default`.
/// `None` if input ends first.
fn ask(
    input: &mut impl BufRead,
    output: &mut impl Write,
    default: Option<&str>,
    prompt: &str,
    check: impl Fn(&str) -> Result<String, Error>,
) -> Result<Option<String>, Error> {
    loop {
        match default {
            Some(default) => write!(output, "{prompt} [{default}]: ")?,
            None => write!(output, "{prompt}: ")?,
        }
        output.flush()?;
        let mut line = String::new();
        if input.read_line(&mut line)? == 0 {
            writeln!(output)?;
            return Ok(None);
        }
        let answer = match (line.trim(), default) {
            ("", Some(default)) => default,
            ("", None) => continue,
            (answer, _) => answer,
        };
        match check(answer) {
            Ok(value) => return Ok(Some(value)),
            Err(error) => writeln!(output, "  {error}")?,
        }
    }
}

/// A host name or address: not empty, no spaces or quotes.
pub fn host(value: &str) -> Result<String, Error> {
    let value = value.trim();
    if value.is_empty()
        || value
            .chars()
            .any(|c| c.is_whitespace() || c.is_control() || c == '\'')
    {
        return Err(Error::InvalidSetting {
            name: "Postgres host",
            reason: format!("{value:?} is not a host name or address"),
        });
    }
    Ok(value.to_string())
}

/// Print what setup would do, and the files it would write.
fn print_plan(options: &Options, files: &[(PathBuf, String)]) {
    let mut out = std::io::stdout().lock();
    let steps = [
        format!("install {} as {HAZINE_BIN}", current_exe_display()),
        format!(
            "install DuckDB {} as {DUCKDB_BIN} (unless that version is there)",
            options.duckdb_version
        ),
        format!("create system user {USER} with home {HOME} (unless it exists)"),
        format!("install the extensions as {USER}: {EXTENSIONS}"),
        format!(
            "check that the lake attaches (creating the catalog the first time): \
             Postgres {}:{}, data {}",
            options.catalog.host, options.catalog.port, options.storage.data_path
        ),
        "write the files below (an existing, different file is kept as .bak)".into(),
        if options.start {
            "systemctl daemon-reload, enable --now hazine, and restart it if anything changed"
                .into()
        } else {
            "systemctl daemon-reload".into()
        },
    ];
    // Writing the plan to stdout can only fail if stdout is gone, and then
    // there is no one to tell.
    let _ = writeln!(out, "hazine setup would:");
    for (n, step) in steps.iter().enumerate() {
        let _ = writeln!(out, "  {}. {step}", n + 1);
    }
    for (path, content) in files {
        let _ = writeln!(out, "\n==> {} <==\n{content}", path.display());
    }
}

fn current_exe_display() -> String {
    std::env::current_exe()
        .map(|path| path.display().to_string())
        .unwrap_or_else(|_| "this binary".into())
}

/// Copy the running hazine to [`HAZINE_BIN`], unless it is already there.
/// Returns whether it changed.
fn install_self() -> Result<bool, Error> {
    let exe = std::env::current_exe()?;
    let target = Path::new(HAZINE_BIN);
    if same_contents(&exe, target)? {
        tracing::info!(path = HAZINE_BIN, "hazine is installed");
        return Ok(false);
    }
    install_binary(&exe, target)?;
    tracing::info!(path = HAZINE_BIN, from = %exe.display(), "installed hazine");
    Ok(true)
}

/// Whether `a` and `b` hold the same bytes; false if `b` does not exist.
fn same_contents(a: &Path, b: &Path) -> Result<bool, Error> {
    match std::fs::read(b) {
        Ok(existing) => Ok(std::fs::read(a)? == existing),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error.into()),
    }
}

/// Download and install DuckDB `version`, unless [`DUCKDB_BIN`] is it.
/// Returns whether it changed.
fn install_duckdb(version: &str) -> Result<bool, Error> {
    let wanted = format!("v{}", version.trim_start_matches('v'));
    if let Ok(output) = Command::new(DUCKDB_BIN).arg("-version").output() {
        let found = String::from_utf8_lossy(&output.stdout);
        if found.split_whitespace().next() == Some(wanted.as_str()) {
            tracing::info!(path = DUCKDB_BIN, version = %wanted, "DuckDB is installed");
            return Ok(false);
        }
    }
    let arch = match std::env::consts::ARCH {
        "x86_64" => "amd64",
        "aarch64" => "arm64",
        other => {
            return Err(Error::Unsupported(if other.is_empty() {
                "unknown CPU architecture"
            } else {
                "DuckDB publishes Linux CLIs for x86_64 and aarch64 only"
            }));
        }
    };
    let url = format!(
        "https://github.com/duckdb/duckdb/releases/download/{wanted}/duckdb-cli-linux-{arch}.tar.gz"
    );
    let dir = TempDir::new()?;
    let archive = dir.path().join("duckdb.tar.gz");
    tracing::info!(%url, "downloading DuckDB");
    command(
        Command::new("curl")
            .args([
                "--fail",
                "--silent",
                "--show-error",
                "--location",
                "--output",
            ])
            .arg(&archive)
            .arg(&url),
    )?;
    command(
        Command::new("tar")
            .arg("-xzf")
            .arg(&archive)
            .arg("-C")
            .arg(dir.path())
            .arg("duckdb"),
    )?;
    install_binary(&dir.path().join("duckdb"), Path::new(DUCKDB_BIN))?;
    let output = command(Command::new(DUCKDB_BIN).arg("-version"))?;
    tracing::info!(path = DUCKDB_BIN, version = %output.trim(), "installed DuckDB");
    Ok(true)
}

/// The service account.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Account {
    uid: u32,
    gid: u32,
}

impl Account {
    /// Give `path` to the account, so DuckDB running as it can read it.
    pub(crate) fn chown(&self, path: &Path) -> std::io::Result<()> {
        std::os::unix::fs::chown(path, Some(self.uid), Some(self.gid))
    }
}

/// The existing [`USER`] account; an error if setup has not created it.
pub(crate) fn service_account() -> Result<Account, Error> {
    lookup_account(&std::fs::read_to_string("/etc/passwd")?, USER).ok_or(Error::InvalidSetting {
        name: "user",
        reason: format!("there is no {USER} user; run hazine setup first"),
    })
}

/// Create the [`USER`] system account and its home, unless they exist.
fn ensure_account() -> Result<Account, Error> {
    let account = match lookup_account(&std::fs::read_to_string("/etc/passwd")?, USER) {
        Some(account) => {
            tracing::info!(user = USER, "system user exists");
            account
        }
        None => {
            command(Command::new("useradd").args([
                "--system",
                "--user-group",
                "--home-dir",
                HOME,
                "--create-home",
                "--shell",
                "/usr/sbin/nologin",
                USER,
            ]))?;
            tracing::info!(user = USER, home = HOME, "created system user");
            lookup_account(&std::fs::read_to_string("/etc/passwd")?, USER).ok_or(
                Error::InvalidSetting {
                    name: "user",
                    reason: format!("{USER} is not in /etc/passwd after useradd"),
                },
            )?
        }
    };
    ensure_dir(Path::new(HOME), 0o750, account.uid, account.gid)?;
    ensure_dir(
        &Path::new(HOME).join("tmp"),
        0o750,
        account.uid,
        account.gid,
    )?;
    Ok(account)
}

/// `user`'s uid and gid in `/etc/passwd` content.
fn lookup_account(passwd: &str, user: &str) -> Option<Account> {
    passwd.lines().find_map(|line| {
        let mut fields = line.split(':');
        if fields.next()? != user {
            return None;
        }
        let _password = fields.next()?;
        Some(Account {
            uid: fields.next()?.parse().ok()?,
            gid: fields.next()?.parse().ok()?,
        })
    })
}

/// Run DuckDB as the service account, with SQL on stdin.
fn duckdb_as(account: &Account, sql: &str, env: &[(String, String)]) -> Result<String, Error> {
    duckdb_on(account, None, sql, env)
}

/// Run DuckDB as the service account on `database` (in memory without one),
/// with SQL on stdin; returns its stdout.
pub(crate) fn duckdb_on(
    account: &Account,
    database: Option<&str>,
    sql: &str,
    env: &[(String, String)],
) -> Result<String, Error> {
    use std::os::unix::process::CommandExt;

    let mut cmd = Command::new(DUCKDB_BIN);
    cmd.args(["-no-agent", "-batch", "-bail", "-init", "/dev/null"]);
    if let Some(database) = database {
        cmd.arg(database);
    }
    cmd.uid(account.uid)
        .gid(account.gid)
        .current_dir(HOME)
        .env_clear()
        .env("HOME", HOME)
        .env("PATH", "/usr/local/bin:/usr/bin:/bin")
        .env("NO_COLOR", "1")
        .envs(env.iter().map(|(name, value)| (name, value)));
    command_with_stdin(&mut cmd, sql)
}

fn install_extensions(account: &Account) -> Result<(), Error> {
    duckdb_as(account, EXTENSIONS, &[])?;
    tracing::info!(user = USER, extensions = EXTENSIONS, "installed extensions");
    Ok(())
}

/// Attach the lake as hazine serve will, with the env file's variables, to
/// find bad settings now rather than in the service's restart loop.
fn check_lake(account: &Account, storage: &Storage, env_file: &str) -> Result<(), Error> {
    let env: Vec<(String, String)> = render::parse_env(env_file).into_iter().collect();
    let output = duckdb_as(account, &render::check_sql(storage), &env)
        .map_err(|error| Error::LakeCheck(with_hint(error.to_string())))?;
    tracing::info!(data_path = %storage.data_path, "the lake attaches");
    tracing::debug!(%output, "lake check");
    Ok(())
}

/// `message`, with a likely cause added for errors that don't say it.
fn with_hint(message: String) -> String {
    if message.contains("timeout expired") {
        format!(
            "{message}\nhint: Postgres did not answer; does its firewall allow this \
             host's IPv4 and IPv6 addresses?"
        )
    } else {
        message
    }
}

/// Create `path` if needed, and set its mode and owner.
fn ensure_dir(path: &Path, mode: u32, uid: u32, gid: u32) -> Result<(), Error> {
    use std::os::unix::fs::PermissionsExt;

    std::fs::create_dir_all(path)?;
    std::os::unix::fs::chown(path, Some(uid), Some(gid))?;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))?;
    Ok(())
}

/// Write `content` to `path` atomically, with `mode` and owner. A different
/// existing file is kept as `<path>.bak`. Returns whether the content changed.
fn write_file(path: &Path, content: &str, mode: u32, uid: u32, gid: u32) -> Result<bool, Error> {
    use std::os::unix::fs::PermissionsExt;

    match std::fs::read_to_string(path) {
        Ok(existing) if existing == content => {
            std::os::unix::fs::chown(path, Some(uid), Some(gid))?;
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))?;
            tracing::info!(path = %path.display(), "unchanged");
            return Ok(false);
        }
        Ok(_) => {
            let backup = with_suffix(path, ".bak");
            std::fs::copy(path, &backup)?;
            tracing::info!(path = %path.display(), backup = %backup.display(), "kept the old file");
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(error.into()),
    }
    let tmp = with_suffix(path, ".tmp");
    {
        let mut file = std::fs::File::create(&tmp)?;
        // Restrict before writing, so secrets are never world-readable.
        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(mode))?;
        std::os::unix::fs::chown(&tmp, Some(uid), Some(gid))?;
        file.write_all(content.as_bytes())?;
        file.sync_all()?;
    }
    std::fs::rename(&tmp, path)?;
    tracing::info!(path = %path.display(), "wrote");
    Ok(true)
}

/// Copy an executable to `target` atomically.
fn install_binary(source: &Path, target: &Path) -> Result<(), Error> {
    use std::os::unix::fs::PermissionsExt;

    let tmp = with_suffix(target, ".tmp");
    std::fs::copy(source, &tmp)?;
    std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
    std::fs::rename(&tmp, target)?;
    Ok(())
}

fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
    let mut name = path.as_os_str().to_owned();
    name.push(suffix);
    PathBuf::from(name)
}

/// Run `cmd`, returning its stdout; fail with its stderr.
fn command(cmd: &mut Command) -> Result<String, Error> {
    command_with_stdin(cmd, "")
}

fn command_with_stdin(cmd: &mut Command, stdin: &str) -> Result<String, Error> {
    let program = cmd.get_program().to_string_lossy().into_owned();
    let mut child = cmd
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|source| Error::Spawn {
            program: program.clone().into(),
            source,
        })?;
    if let Some(mut pipe) = child.stdin.take() {
        pipe.write_all(stdin.as_bytes())?;
    }
    let output = child.wait_with_output()?;
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let detail = [stderr.trim(), stdout.trim()]
            .into_iter()
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>()
            .join("\n");
        Err(Error::Command {
            program,
            status: output.status.to_string(),
            detail,
        })
    }
}

/// The effective uid, from `/proc/self/status`.
pub(crate) fn effective_uid() -> Result<u32, Error> {
    let status = std::fs::read_to_string("/proc/self/status")?;
    status
        .lines()
        .find_map(|line| line.strip_prefix("Uid:"))
        .and_then(|ids| ids.split_whitespace().nth(1)?.parse().ok())
        .ok_or(Error::Unsupported("cannot read the effective uid"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn memory_comes_from_meminfo() {
        let meminfo = "MemTotal:       131899664 kB\nMemFree:  1000 kB\n";
        assert_eq!(parse_meminfo(meminfo), Some(125));
        assert_eq!(parse_meminfo("MemFree: 1 kB\n"), None);
    }

    #[test]
    fn accounts_are_found_in_passwd() {
        let passwd = "root:x:0:0:root:/root:/bin/bash\n\
                      hazinex:x:998:998::/x:/bin/sh\n\
                      hazine:x:999:997::/var/lib/hazine:/usr/sbin/nologin\n";
        assert_eq!(
            lookup_account(passwd, "hazine"),
            Some(Account { uid: 999, gid: 997 })
        );
        assert_eq!(lookup_account(passwd, "nobody"), None);
    }

    fn answers(input: &str, default: Option<&str>) -> (Option<String>, String) {
        let mut output = Vec::new();
        let value = ask(
            &mut std::io::Cursor::new(input),
            &mut output,
            default,
            "Data path",
            render::data_path,
        )
        .unwrap();
        (value, String::from_utf8(output).unwrap())
    }

    #[test]
    fn asking_takes_the_answer_or_the_default() {
        let (value, prompt) = answers("s3://lake/x\n", Some("s3://old/"));
        assert_eq!(value.as_deref(), Some("s3://lake/x/"));
        assert_eq!(prompt, "Data path [s3://old/]: ");

        let (value, _) = answers("\n", Some("s3://old/"));
        assert_eq!(value.as_deref(), Some("s3://old/"));
    }

    #[test]
    fn asking_repeats_until_the_answer_is_valid() {
        let (value, prompt) = answers("\nlake\ns3://lake\n", None);
        assert_eq!(value.as_deref(), Some("s3://lake/"));
        assert_eq!(prompt.matches("Data path: ").count(), 3, "{prompt}");
        assert!(prompt.contains("does not start with s3://"), "{prompt}");
    }

    #[test]
    fn asking_gives_up_when_input_ends() {
        let (value, _) = answers("lake\n", None);
        assert_eq!(value, None);
    }

    #[test]
    fn hosts_are_checked() {
        assert_eq!(host(" db.example.org ").unwrap(), "db.example.org");
        assert_eq!(host("10.0.0.5").unwrap(), "10.0.0.5");
        for bad in ["", "db example", "db'x"] {
            assert!(host(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn connect_timeouts_get_a_hint() {
        assert!(with_hint("x: timeout expired".into()).contains("firewall"));
        assert_eq!(
            with_hint("password authentication failed".into()),
            "password authentication failed"
        );
    }

    #[test]
    fn suffixes_are_appended() {
        assert_eq!(
            with_suffix(Path::new("/etc/hazine/hazine.env"), ".bak"),
            PathBuf::from("/etc/hazine/hazine.env.bak")
        );
    }
}