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
// Copyright 2023-2024 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2
#![deny(clippy::pedantic)]
#![deny(clippy::unwrap_used)]

use std::{
    fs::File,
    io::{read_to_string, Seek, Write},
    path::PathBuf,
    sync::Arc,
    time::Duration,
};

use anyhow::{bail, Context};
use camino::Utf8PathBuf;
use config::{open_default_path, parse_config};
use log::{debug, error, info, trace, warn};
use rustix::fs::sync;
use stdio::{StdIo, StdIoLock};
use tempfile::NamedTempFile;
use tokio::{sync::Mutex, task::JoinSet};
use vstorage::{
    base::{IcsItem, Item, Storage, VcardItem},
    sync::{
        declare::StoragePair,
        plan::{ItemAction, Plan},
        status::{StatusDatabase, StatusError},
        SyncError,
    },
    Etag,
};

use crate::cli::{Cli, Command};

mod cli;
mod config;
mod stdio;
mod tls;

pub const VERSION: &str = "2.0.0-alpha0";

/// Pair with a name, as defined in the configuration file.
pub(crate) struct NamedPair<I: Item> {
    name: String,
    pub(crate) inner: StoragePair<I>,
    status_path: Utf8PathBuf,
    conflict_resolution: Option<RawCommand>,
    /// Discretionary locks taken before using a storage.
    /// These MUST be sorted based on storage name to prevent possible deadlocks.
    locks: (Arc<Mutex<()>>, Arc<Mutex<()>>),
    names: (String, String),
}

/// Data necessary to create a new `Command` instance.
///
/// This helper is used for commands that need to be executed multiple times.
pub struct RawCommand {
    command: String,
    args: Vec<String>,
}

impl RawCommand {
    #[must_use]
    pub fn command(&self) -> std::process::Command {
        let mut cmd = std::process::Command::new(&self.command);
        cmd.args(&self.args);
        cmd
    }
}

/// Simply log non-fatal errors.
#[allow(clippy::needless_pass_by_value)]
pub fn log_error(error: SyncError) {
    error!("{error}");
}

impl<I: Item> NamedPair<I> {
    // TODO: interval should be per-storage.

    /// Sync this pair indefinitely
    ///
    /// Returns an error if an only if a fatal synchronisation error occurred.
    async fn daemon(self, interval: Duration) -> StatusError {
        loop {
            if let Err(err) = self.sync_once(false).await {
                error!("Error synchronising {}: {}", self.name, err);
                if let Ok(status_error) = err.downcast::<StatusError>() {
                    return status_error;
                };
                // If error was a transient error, continue.
            };

            warn!(
                "Monitoring is not implemented, will auto-sync every {} minutes.",
                interval.as_secs() / 60
            );
            tokio::time::sleep(interval).await;
        }
    }

    async fn sync_once(&self, dry_run: bool /* ui-lock ? */) -> anyhow::Result<()> {
        let lock_0 = self.locks.0.lock().await;
        let lock_1 = self.locks.1.lock().await;
        let plan = self.create_plan().await?;
        self.print_plan(&plan);
        if !dry_run {
            let status_rw = StatusDatabase::open_or_create(&self.status_path)
                .with_context(|| format!("open_or_create status db for {}", self.name))?;
            plan.execute(&status_rw, log_error).await?;
        }
        // Explicitly drop these here to ensure they survive up to this point.
        drop(lock_0);
        drop(lock_1);
        Ok(())
    }

    async fn create_plan(&self) -> anyhow::Result<Plan<I>> {
        debug!("Creating plan for storage pair '{}'.", self.name);
        let status_ro = StatusDatabase::open_readonly(&self.status_path)
            .with_context(|| format!("open_readonly status db for {}", self.name))?;
        Ok(Plan::new(&self.inner, status_ro.as_ref()).await?)
    }

    async fn discover(&self) -> anyhow::Result<()> {
        // TODO: discover displaynames and colours too
        let disco = self.inner.storage_a().discover_collections().await?;
        println!("For pair {}, storage a/{}:", self.name, self.names.0);
        for collection in disco.collections() {
            println!("- id={} href={}", collection.id(), collection.href());
        }

        let disco = self.inner.storage_b().discover_collections().await?;
        println!("For pair {}, storage b/{}:", self.name, self.names.1);
        for collection in disco.collections() {
            println!("- id={} href={}", collection.id(), collection.href());
        }

        Ok(())
    }

    fn print_plan(&self, plan: &Plan<I>) {
        // TODO: need to lock stdout/stderr for concurrent runs.
        info!(">>> Plan for storage pair '{}'", self.name);
        for cp in &plan.collection_plans {
            info!(
                "collection: {}, action: {}. {} item actions. {} property actions.",
                cp.alias(),
                cp.collection_action,
                cp.item_actions.len(),
                cp.property_actions.len(),
            );

            for item in &cp.item_actions {
                info!("item: {}", item);
                debug!("{item:?}");
            }
            for prop in &cp.property_actions {
                info!("property: {:?}", prop);
            }
        }
    }

    async fn resolve_conflicts(self, stdio: Arc<StdIo>) -> anyhow::Result<()> {
        // TODO: are storage locks necessary here?
        let Some(ref raw_cmd) = self.conflict_resolution else {
            error!("No conflict resolution command for {}.", self.name);
            return Ok(());
        };
        info!("Resolving conflicts for pair {}.", self.name);

        let plan = self.create_plan().await?;
        self.print_plan(&plan);

        // TODO: when we parallelise, should take lock on stdin here.

        let conflicts = plan
            .collection_plans
            .into_iter()
            .flat_map(|cp| cp.item_actions)
            .filter_map(|action| match action {
                ItemAction::Conflict { a, b, .. } => Some((a, b)),
                _ => None,
            })
            // Collect in order to compute the total amount (for display purposes).
            .collect::<Vec<_>>();

        let total = conflicts.len();

        trace!("Taking stdio lock...");
        let lock = stdio.lock().await;
        trace!("Stdio lock taken.");

        for (i, (a, b)) in conflicts.into_iter().enumerate() {
            println!("Next is item {}/{total}", i + 1);
            continue_or_abort(&lock)?;

            // TODO: improve logging here.
            // TODO: move duplicated logic into a "read_item_to_tempfile" function.
            let (mut temp_a, etag_a) = save_item_to_tempfile(self.inner.storage_a(), &a.href)
                .await
                .context("fetching conflicted item from A")?;
            let (mut temp_b, etag_b) = save_item_to_tempfile(self.inner.storage_b(), &b.href)
                .await
                .context("fetching conflicted item from B")?;

            info!("Running conflict resolution for item {}", a.uid);
            let exit_status = raw_cmd
                .command()
                .arg(temp_a.path())
                .arg(temp_b.path())
                .spawn()
                .context("executing conflict resolution command")?
                .wait()
                .context("waiting for conflict resolution command")?;

            if !exit_status.success() {
                error!("Conflict resolution command failed: {exit_status}");
                continue;
            }

            // Ensure that files are committed; otherwise we sometimes read empty data.
            sync();
            temp_a.rewind().context("seeking in temporary file for A")?;
            temp_b.rewind().context("seeking in temporary file for B")?;

            let new_a = read_to_string(temp_a).context("reading resolved item A")?;
            let new_b = read_to_string(temp_b).context("reading resolved item B")?;

            if new_a.is_empty() {
                error!("Resolved item A is empty.");
                continue;
            }
            if new_b.is_empty() {
                error!("Resolved item B is empty.");
                continue;
            }
            if new_a.trim() != new_b.trim() {
                error!("Conflict resolution yielded mismatching items; skipping");
                continue;
            }

            let new = I::from(new_a);
            drop(new_b);

            self.inner
                .storage_a()
                .update_item(&a.href, &etag_a, &new)
                .await
                .context("uploading resolved item into A")?;
            debug!("Uploaded resolved item to A.");

            self.inner
                .storage_b()
                .update_item(&b.href, &etag_b, &new)
                .await
                .context("uploading resolved item into B")?;
            debug!("Uploaded resolved item to B.");

            info!("Resolved conflicts for '{}'.", new.ident());
        }

        Ok(())
    }
}

async fn save_item_to_tempfile<I: Item>(
    storage: &dyn Storage<I>,
    href: &str,
) -> anyhow::Result<(NamedTempFile, Etag)> {
    let mut temp =
        NamedTempFile::new().context("creating temporary file for conflict resolution")?;
    debug!("Fetching {href} for conflict resolution...");
    let (data, etag) = storage
        .get_item(href)
        .await
        .context("fetching conflicting item from a")?;
    temp.write_all(data.as_str().as_bytes())
        .context("writing item into temporary file")?;

    Ok((temp, etag))
}

/// Returns an error if user chooses to abort.
fn continue_or_abort(stdio: &StdIoLock) -> anyhow::Result<()> {
    let input = stdio.stdin();

    loop {
        println!("Continue? [Y/n]");
        // Need to read entire lines because the stdlib implicitly buffers stdin.
        let mut response = String::new();
        input
            .read_line(&mut response)
            .context("Reading response from stdin")?;

        match response.trim().to_lowercase().as_str() {
            "" | "y" => return Ok(()),
            "n" => bail!("Aborted by user."),
            _ => {}
        };
    }
}

pub(crate) struct App {
    interval: Duration,
    calendar_pairs: Vec<NamedPair<IcsItem>>,
    contact_pairs: Vec<NamedPair<VcardItem>>,
    stdio: Arc<StdIo>,
}

impl App {
    async fn discover(&self) -> anyhow::Result<()> {
        // FIXME: if multiple pairs share a storage, only print that storage once.
        for pair in &self.calendar_pairs {
            pair.discover().await?;
        }
        for pair in &self.contact_pairs {
            pair.discover().await?;
        }
        Ok(())
    }

    async fn daemon(self) -> anyhow::Result<()> {
        let mut set = JoinSet::new();
        for pair in self.calendar_pairs {
            set.spawn(pair.daemon(self.interval));
        }
        for pair in self.contact_pairs {
            set.spawn(pair.daemon(self.interval));
        }

        while let Some(res) = set.join_next().await {
            match res {
                Ok(err) => error!("Error in sync task: {}.", err),
                Err(joinerr) => error!("Sync task aborted: {}.", joinerr),
            }
        }
        anyhow::bail!("All sync tasks exited.");
    }

    async fn sync(self, dry_run: bool) -> anyhow::Result<()> {
        let mut set = JoinSet::new();
        for pair in self.calendar_pairs {
            set.spawn(async move { pair.sync_once(dry_run).await });
        }
        for pair in self.contact_pairs {
            set.spawn(async move { pair.sync_once(dry_run).await });
        }

        while let Some(res) = set.join_next().await {
            match res {
                Ok(Ok(())) => {}
                Ok(Err(err)) => error!("Error in sync task: {}.", err),
                Err(joinerr) => error!("Sync task aborted: {}.", joinerr),
            }
        }
        Ok(())
    }

    async fn resolve_conflicts(self, dry_run: bool) -> anyhow::Result<()> {
        if dry_run {
            bail!("dry_run is not implemented for resolve-conflicts");
        }

        let mut set = JoinSet::new();
        for pair in self.calendar_pairs {
            set.spawn(pair.resolve_conflicts(self.stdio.clone()));
        }
        for pair in self.contact_pairs {
            set.spawn(pair.resolve_conflicts(self.stdio.clone()));
        }

        while let Some(res) = set.join_next().await {
            match res {
                Ok(Ok(())) => {}
                Ok(Err(err)) => error!("Error resolving conflicts: {}.", err),
                Err(joinerr) => error!("Sync task aborted: {}.", joinerr),
            }
        }
        Ok(())
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse(std::env::args()).unwrap_or_else(|err| {
        eprintln!("Bad usage: {err}\n");
        eprintln!("Usage: pimsync [-c CONFIGFILE ] [-v LOGLEVEL] [-p PAIR] COMMAND [ARGS...]");
        eprintln!("Commands:");
        eprintln!("\tcheck\t\t\tcheck configuration and exit");
        eprintln!("\tdaemon -[r READY_FD]\tkeep storages in sync");
        eprintln!("\tsync [-d]\t\tsync storages once");
        eprintln!("\tresolve-conflicts [-d]\tmanually resolve conflicts");
        eprintln!("\tdiscover\t\tprint discovered collections");
        eprintln!("\tversion\t\t\tprint version");
        eprintln!("See 'man pimsync' for details");
        std::process::exit(100);
    });

    if let Command::Version = cli.command {
        println!("pimsync {VERSION}");
        return Ok(());
    };

    simple_logger::SimpleLogger::new()
        .with_level(cli.log_level)
        .init()
        .expect("logger should initialise");
    info!("Logging enabled with {} level", cli.log_level);

    let (config_path, config_file) = match cli.config_file {
        Some(file) => {
            let path = PathBuf::from(file);
            let file = File::open(&path)
                .with_context(|| format!("Could not open {}.", path.to_string_lossy()))?;
            debug!("Opened config file {}", path.to_string_lossy());
            (path, file)
        }
        None => open_default_path()?,
    };

    let config_data = read_to_string(config_file)?;
    let config = parse_config(&config_data, &cli.pairs).with_context(|| {
        format!(
            "Could not parse configuration file at {}",
            config_path.display()
        )
    })?;
    trace!("Parsed configuration: {:?}", &config);

    let app = config
        .into_app()
        .await
        .context("initialising application")?;
    debug!("Initialised application");

    match cli.command {
        Command::Check => Ok(()),
        Command::Daemon { ready_fd } => {
            // Everything is ready; indicate this before actual daemon work.
            if let Some(mut f) = ready_fd {
                f.write_all(b"READY=1\n")
                    .context("writing to readiness fd")?;
                // File is closed implicitly here.
            };
            app.daemon().await
        }
        Command::Sync { dry_run } => app.sync(dry_run).await,
        Command::ResolveConflicts { dry_run } => app.resolve_conflicts(dry_run).await,
        Command::Discover => app.discover().await,
        Command::Version => unreachable!(),
    }

    // TODO: turn storages into lockables
    // TODO: create per-pair tasks and sync pairs in parallel.
}