// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! `xdg-desktop-portal-crustace` — Crustace backend for the freedesktop
//! [Portal] specification.
//!
//! The freedesktop `xdg-desktop-portal` daemon is the broker that
//! sandboxed apps (Flatpak) call when they need a system-level
//! resource: file chooser, notification, camera, location, screencast,
//! etc. Each desktop environment provides a *backend* implementation
//! that owns the actual UX — `xdg-desktop-portal-gnome`,
//! `xdg-desktop-portal-kde`, `xdg-desktop-portal-hyprland`, and so on.
//! This crate is the Crustace backend: it registers the well-known bus
//! name `org.freedesktop.impl.portal.desktop.crustace` and serves the
//! portal interfaces this DE owns.
//!
//! [Portal]: https://flatpak.github.io/xdg-desktop-portal/

mod notification;

use anyhow::Context;
use tracing_subscriber::EnvFilter;

const SERVICE_NAME: &str = "org.freedesktop.impl.portal.desktop.crustace";
const SERVICE_PATH: &str = "/org/freedesktop/portal/desktop";

#[ tokio::main ]
async fn main() -> anyhow::Result<()>
{
	// Honour `RUST_LOG=...` so operators can crank up tracing without a
	// rebuild; default to INFO so the first run is informative without
	// being noisy.
	tracing_subscriber::fmt()
		.with_env_filter( EnvFilter::try_from_default_env().unwrap_or_else( | _ | EnvFilter::new( "info" ) ) )
		.init();

	let connection = zbus::connection::Builder::session()
		.context( "open session bus" )?
		.name( SERVICE_NAME )
		.context( "configure well-known name" )?
		.serve_at( SERVICE_PATH, notification::NotificationPortal::new() )
		.context( "register Notification portal at portal path" )?
		.build()
		.await
		.context( "claim bus name + start serving" )?;

	tracing::info!( name = SERVICE_NAME, path = SERVICE_PATH, "xdg-desktop-portal-crustace online" );

	// Idle until the supervisor (systemd-user / D-Bus activation) tells
	// us to stop. Keeping the `connection` in scope is what keeps the
	// portal alive — drop ends serving.
	tokio::signal::ctrl_c().await.context( "wait for shutdown signal" )?;
	tracing::info!( "shutdown signal received, exiting cleanly" );
	drop( connection );
	Ok(())
}
