//! Persistence of the last username that logged in through the greeter, so the
//! field comes pre-filled on the next boot. Stored under the greeter user's
//! XDG config (`_loginmanager` in production, `$XDG_CONFIG_HOME` under
//! `make start`). Lock mode never touches this — its user is fixed.

use std::path::PathBuf;

fn last_user_path() -> Option<PathBuf>
{
	let base = std::env::var_os( "XDG_CONFIG_HOME" )
		.map( PathBuf::from )
		.filter( |p| p.is_absolute() )
		.or_else( || std::env::var_os( "HOME" ).map( |h| PathBuf::from( h ).join( ".config" ) ) )?;
	Some( base.join( "eydos-loginmanager" ).join( "last-user" ) )
}

pub fn load_last_user() -> Option<String>
{
	let raw  = std::fs::read_to_string( last_user_path()? ).ok()?;
	let user = raw.trim();
	if user.is_empty() { None } else { Some( user.to_string() ) }
}

pub fn save_last_user( user: &str )
{
	let Some( path ) = last_user_path() else { return; };
	if let Some( dir ) = path.parent()
	{
		let _ = std::fs::create_dir_all( dir );
	}
	let _ = std::fs::write( path, user );
}
