//! Entry point for `calllogs-server`.
//!
//! Boot sequence: open SQLite (running migrations), register
//! `org.liberux.CallLog1` on the session bus, then park forever so the
//! connection — and therefore the service name — stays alive.

mod config;
mod db;
mod dbus;
mod model;

use std::sync::Arc;

use anyhow::{ Context, Result };

fn main() -> Result<()>
{
	env_logger::Builder::from_env(
		env_logger::Env::default().default_filter_or( "info" ),
	).init();

	let paths = config::Paths::resolve().context( "resolving XDG paths" )?;
	paths.ensure_dirs().context( "ensuring data dir" )?;
	log::info!( "data dir: {}", paths.data_dir.display() );

	let database = Arc::new(
		db::Database::open( &paths.calllog_db )
			.with_context( || format!( "opening {}", paths.calllog_db.display() ) )?,
	);

	smol::block_on( async
	{
		// `_conn` stays in scope for the whole block, keeping the well-known
		// name registered; dropping it would tear the service down.
		let _conn = dbus::serve( database.clone() )
			.await
			.context( "registering D-Bus service" )?;
		log::info!(
			"D-Bus service registered: {} at {}",
			dbus::SERVICE_NAME, dbus::OBJECT_PATH,
		);

		std::future::pending::<()>().await;
		Ok::<(), anyhow::Error>( () )
	} )?;

	Ok( () )
}
