use std::io::Write;
use std::path::Path;
use serde_json::{Value, json};
use super::consent::Offer;
use super::drive::{Outcome, Run, drive};
use super::journal::{self, Journal, Stage, Unit};
use super::link::Link;
use super::report::{self, Offered};
use super::snapshot::{self, Snapshot};
use crate::login::Login;
use crate::login::host::{self, Result};
use crate::login::local::{self, State};
use crate::login::output::{Mark, View, fill, host as shown, lost, say};
use crate::profile::files;
use crate::store::time::Stamp;
pub(crate) enum Route {
Login,
Resume(Box<Journal>),
Discard,
Finish,
}
pub(crate) fn route(args: &Login) -> Result<Route> {
route_at(args, &files::home()?)
}
pub(super) fn route_at(args: &Login, home: &Path) -> Result<Route> {
if args.import && local::environment().is_some() {
return Err(say("import_environment"));
}
if args.discard_import {
return Ok(Route::Discard);
}
match journal::read(home)? {
Some(done) if done.stage == Stage::Succeeded => {
let connected = match local::state(home) {
Ok(state) => state.is_some_and(|s| !s.signed_out),
Err(_) => true,
};
Ok(if connected {
Route::Finish
} else {
Route::Login
})
}
Some(waiting) if args.import => Ok(Route::Resume(Box::new(waiting))),
Some(waiting) if !args.refresh => {
Err(fill("import_waiting", &[("host", &shown(&waiting.host))]))
}
_ => Ok(Route::Login),
}
}
fn personal(units: &[Unit]) -> Option<String> {
let scope = crate::home::user_mount().ok()?.scope;
units
.iter()
.any(|u| u.kind == "scope" && u.name == scope)
.then_some(scope)
}
pub(super) fn offered(
mut offer: Offer,
verbose: bool,
ui: &mut View<impl Write>,
) -> Result<(Value, u8, Vec<String>)> {
let home = offer.home.clone();
let _op = (offer.held.take()).ok_or("the login lock was released before the import")?;
let state = local::state(&home)?.ok_or("the machine login is missing")?;
if state.host != offer.host
|| offer
.account
.as_ref()
.is_some_and(|a| *a != state.account.id)
{
return Err(say("import_other_account"));
}
let approved = offer.credential.clone().unwrap_or_default();
if state.credential_digest != approved {
return Err(say("import_other_credential"));
}
let token = state.token(&home)?;
let journal = Journal {
journal_format: 1,
host: offer.host.clone(),
import_endpoint: offer.endpoint.clone(),
account: state.account.id.clone(),
credential: approved,
snapshot: offer.snapshot.id.clone(),
begun_at: Stamp::now().iso(),
personal: personal(&offer.units),
units: offer.units.clone(),
local: offer.local.clone(),
session: None,
omitted: Vec::new(),
refused: Vec::new(),
stage: Stage::Begin,
targets: Vec::new(),
};
journal::write(&home, &journal)?;
offer.armed = true;
let offered = Offered::of(&journal.units);
let words = [
(
"units",
report::count(offered.scopes + offered.conversations, "unit"),
),
("size", report::size(offered.bytes)),
("host", shown(&state.discovery.name)),
];
let pairs: Vec<(&str, &str)> = words.iter().map(|(k, v)| (*k, v.as_str())).collect();
ui.step(&say("step_import"))
.and_then(|()| ui.say(&fill("import_sending", &pairs)))
.map_err(lost)?;
session_run(
&home,
&state,
&token,
journal,
Some(&offer.snapshot),
verbose,
ui,
)
}
fn session_run(
home: &Path,
state: &State,
token: &str,
mut journal: Journal,
snapshot: Option<&Snapshot>,
verbose: bool,
ui: &mut View<impl Write>,
) -> Result<(Value, u8, Vec<String>)> {
let link = Link::new(&state.host, token)?;
let outcome = {
let mut run = Run {
link: &link,
home,
origin: &state.host,
ui,
verbose,
};
drive(&mut run, &mut journal, snapshot)
};
let mut next = report::outcome(ui, &outcome, &journal).map_err(lost)?;
if let Outcome::Succeeded(targets) = &outcome {
journal.stage = Stage::Succeeded;
journal.targets = targets.clone();
journal::write(home, &journal)?;
let _ = snapshot::release(home);
} else if outcome.terminal() {
snapshot::dispose(home).map_err(|f| f.message())?;
} else if journal::write(home, &journal).is_err() {
next.push(say("next_resume_import"));
}
let code = u8::from(matches!(outcome, Outcome::Stopped(_) | Outcome::Failed(..)));
Ok((report::json(&outcome, &journal), code, next))
}
pub(super) fn resumed(
args: &Login,
routed: Journal,
ui: &mut View<impl Write>,
) -> Result<(Value, u8, Vec<String>)> {
resumed_at(args, routed, &files::home()?, ui)
}
pub(super) fn resumed_at(
args: &Login,
routed: Journal,
home: &Path,
ui: &mut View<impl Write>,
) -> Result<(Value, u8, Vec<String>)> {
let home = home.to_path_buf();
let _op = local::lock(&home)?;
let Some(journal) = journal::read(&home)? else {
let words = [
("host", shown(&routed.host)),
("at", shown(&routed.begun_at)),
];
let pairs: Vec<(&str, &str)> = words.iter().map(|(k, v)| (*k, v.as_str())).collect();
ui.step(&say("step_import"))
.and_then(|()| ui.mark(Mark::Ok, &fill("import_gone", &pairs)))
.map_err(lost)?;
return Ok((json!({"status": "gone"}), 0, Vec::new()));
};
if args.host.as_deref().is_some_and(|h| h != journal.host) {
return Err(fill(
"import_other_host",
&[("host", &shown(&journal.host))],
));
}
let state = local::state(&home)?.ok_or_else(|| say("import_other_credential"))?;
if state.host != journal.host {
return Err(fill(
"import_other_host",
&[("host", &shown(&journal.host))],
));
}
if state.account.id != journal.account {
return Err(say("import_other_account"));
}
if state.signed_out || state.credential_digest != journal.credential {
return Err(say("import_other_credential"));
}
let token = state
.token(&home)
.map_err(|_| say("import_other_credential"))?;
let agent = host::agent(15)?;
let machine = &state.discovery.machine_endpoint;
let fetched = host::fetch(&agent, &state.host, machine, &token, None)
.map_err(|e| fill("import_unreachable", &[("reason", &e)]))?;
match fetched {
Some((doc, _)) if doc.account.id == journal.account => {}
_ => return Err(say("import_other_account")),
}
let opened = snapshot::open(&home).map_err(|f| f.message())?;
let snapshot = opened.filter(|s| s.id == journal.snapshot);
if snapshot.is_none() && matches!(journal.stage, Stage::Begin | Stage::Transfer) {
return Err(say("import_copy_gone"));
}
let at = shown(&journal.begun_at);
ui.step(&say("step_import"))
.and_then(|()| {
ui.say(&fill(
"import_resuming",
&[("host", &shown(&state.discovery.name)), ("at", &at)],
))
})
.map_err(lost)?;
session_run(
&home,
&state,
&token,
journal,
snapshot.as_ref(),
args.verbose,
ui,
)
}