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
// Copyright (C) 2022-2023 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: GPL-3.0-or-later

#![allow(clippy::let_and_return, clippy::let_unit_value)]
#![warn(clippy::dbg_macro, clippy::unwrap_used)]

#[macro_use]
mod redefine;

mod args;
#[doc(hidden)]
pub mod btrfs;
mod ops;
mod repo;
#[doc(hidden)]
pub mod snapshot;
#[allow(clippy::unwrap_used)]
#[cfg(any(test, feature = "test"))]
pub mod test;
#[doc(hidden)]
pub mod util;

use std::borrow::Cow;
use std::ffi::OsString;
use std::fs::canonicalize;
use std::path::Path;
use std::path::PathBuf;

use anyhow::Context as _;
use anyhow::Error;
use anyhow::Result;

use clap::error::ErrorKind;
use clap::Parser as _;

use crate::args::Args;
use crate::args::Backup;
use crate::args::Command;
use crate::args::Purge;
use crate::args::RemoteCommand;
use crate::args::Restore;
use crate::args::Snapshot;
use crate::args::Tag;
use crate::btrfs::trace_commands;
use crate::btrfs::Btrfs;
use crate::ops::RemoteOps;
use crate::repo::backup as backup_subvol;
use crate::repo::purge as purge_subvol;
use crate::repo::restore as restore_subvol;
use crate::repo::Repo;
use crate::util::canonicalize_non_strict;


/// A helper function for creating a btrfs repository in the provided
/// directory, taking care of all error annotations.
fn create_repo(directory: &Path, remote_command: Option<(String, Vec<String>)>) -> Result<Repo> {
  let mut builder = Repo::builder();

  if let Some((command, args)) = remote_command {
    let ops = RemoteOps::new(command.clone(), args.clone());
    let () = builder.set_file_ops(ops);

    let btrfs = Btrfs::with_command_prefix(command, args);
    let () = builder.set_btrfs_ops(btrfs);
  }

  let repo = builder.build(directory).with_context(|| {
    format!(
      "failed to create btrfs snapshot repository at {}",
      directory.display()
    )
  })?;

  Ok(repo)
}


/// Perform an operation on a bunch of subvolumes, providing either a
/// single repository at the provided path or create a new one
/// co-located to each subvolume.
fn with_repo_and_subvols<F>(repo_path: Option<&Path>, subvols: &[PathBuf], f: F) -> Result<()>
where
  F: FnMut(&Repo, &Path) -> Result<()>,
{
  let mut f = f;

  let repo = if let Some(repo_path) = repo_path {
    Some(create_repo(repo_path, None)?)
  } else {
    None
  };

  let () = subvols.iter().try_for_each::<_, Result<()>>(|subvol| {
    let repo = if let Some(repo) = &repo {
      Cow::Borrowed(repo)
    } else {
      let directory = subvol.parent().with_context(|| {
        format!(
          "subvolume {} does not have a parent; need repository path",
          subvol.display()
        )
      })?;
      Cow::Owned(create_repo(directory, None)?)
    };

    f(&repo, subvol)
  })?;

  Ok(())
}


/// Handler for the `backup` sub-command.
fn backup(backup: Backup) -> Result<()> {
  let Backup {
    mut subvolumes,
    destination,
    source,
    tag: Tag { tag },
    remote_command: RemoteCommand { remote_command },
  } = backup;

  let () = subvolumes.iter_mut().try_for_each(|subvol| {
    *subvol = canonicalize(&subvol)?;
    Result::<(), Error>::Ok(())
  })?;

  let dst = create_repo(&destination, remote_command)?;

  with_repo_and_subvols(source.as_deref(), subvolumes.as_slice(), |src, subvol| {
    let _snapshot = backup_subvol(src, &dst, subvol, &tag)
      .with_context(|| format!("failed to backup subvolume {}", subvol.display()))?;
    Ok(())
  })
}


/// Handler for the `restore` sub-command.
fn restore(restore: Restore) -> Result<()> {
  let Restore {
    mut subvolumes,
    destination,
    source,
    remote_command: RemoteCommand { remote_command },
    snapshots_only,
  } = restore;

  let () = subvolumes.iter_mut().try_for_each(|subvol| {
    *subvol = canonicalize_non_strict(subvol)?;
    Result::<(), Error>::Ok(())
  })?;

  let src = create_repo(&source, remote_command)?;

  with_repo_and_subvols(
    destination.as_deref(),
    subvolumes.as_slice(),
    |dst, subvol| {
      let _snapshot = restore_subvol(&src, dst, subvol, snapshots_only)
        .with_context(|| format!("failed to restore subvolume {}", subvol.display()))?;
      Ok(())
    },
  )
}


/// Handler for the `purge` sub-command.
fn purge(purge: Purge) -> Result<()> {
  let Purge {
    mut subvolumes,
    source,
    destination,
    tag: Tag { tag },
    remote_command: RemoteCommand { remote_command },
    keep_for,
  } = purge;

  let () = subvolumes.iter_mut().try_for_each(|subvol| {
    *subvol = canonicalize_non_strict(subvol)?;
    Result::<(), Error>::Ok(())
  })?;

  if let Some(destination) = destination {
    let repo = create_repo(&destination, remote_command)?;

    let () = subvolumes
      .iter()
      .try_for_each(|subvol| purge_subvol(&repo, subvol, &tag, keep_for))?;
  }

  // TODO: This logic is arguably a bit sub-optimal for the single-repo
  //       case, because we list snapshots for each subvolume.
  with_repo_and_subvols(source.as_deref(), subvolumes.as_slice(), |repo, subvol| {
    purge_subvol(repo, subvol, &tag, keep_for)
  })
}


/// Handler for the `snapshot` sub-command.
fn snapshot(snapshot: Snapshot) -> Result<()> {
  let Snapshot {
    repository,
    mut subvolumes,
    tag: Tag { tag },
  } = snapshot;

  let () = subvolumes.iter_mut().try_for_each(|subvol| {
    *subvol = canonicalize(&subvol)?;
    Result::<(), Error>::Ok(())
  })?;

  with_repo_and_subvols(
    repository.as_deref(),
    subvolumes.as_slice(),
    |repo, subvol| {
      let _snapshot = repo
        .snapshot(subvol, &tag)
        .with_context(|| format!("failed to snapshot subvolume {}", subvol.display()))?;
      Ok(())
    },
  )
}


/// Run the program and report errors, if any.
pub fn run<A, T>(args: A) -> Result<()>
where
  A: IntoIterator<Item = T>,
  T: Into<OsString> + Clone,
{
  let args = match Args::try_parse_from(args) {
    Ok(args) => args,
    Err(err) => match err.kind() {
      ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => {
        print!("{}", err);
        return Ok(())
      },
      _ => return Err(err).context("failed to parse program arguments"),
    },
  };

  if args.trace {
    let () = trace_commands();
  }

  match args.command {
    Command::Backup(backup) => self::backup(backup),
    Command::Purge(purge) => self::purge(purge),
    Command::Restore(restore) => self::restore(restore),
    Command::Snapshot(snapshot) => self::snapshot(snapshot),
  }
}


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

  use std::ffi::OsStr;


  /// Check that we do not error out on the --version option.
  #[test]
  fn version() {
    let args = [OsStr::new("btrfs-backup"), OsStr::new("--version")];
    let () = run(args).unwrap();
  }

  /// Check that we do not error out on the --help option.
  #[test]
  fn help() {
    let args = [OsStr::new("btrfs-backup"), OsStr::new("--help")];
    let () = run(args).unwrap();
  }
}