use std::fs::{self, Permissions};
use std::io::{self, Write};
use std::os::unix::fs::PermissionsExt;
use anyhow::Result;
use rustfm_scrobble::Scrobbler;
use crate::config::config_dir;
const SESSION_FILE: &str = "session";
pub fn authenticate(scrobbler: &mut Scrobbler) -> Result<()> {
let mut path = config_dir()?;
path.push(SESSION_FILE);
if let Ok(session_key) = fs::read_to_string(&path) {
scrobbler.authenticate_with_session_key(&session_key);
} else {
let mut input = String::new();
print!(
"Log in to Last.fm\n\
Username: "
);
io::stdout().flush()?;
io::stdin().read_line(&mut input)?;
input.pop();
let username = input.clone();
input.clear();
print!("Password: ");
io::stdout().flush()?;
io::stdin().read_line(&mut input)?;
input.pop();
let password = input;
let session_response = scrobbler.authenticate_with_password(&username, &password)?;
let _ = fs::write(&path, session_response.key);
let _ = fs::set_permissions(&path, Permissions::from_mode(0o600));
}
Ok(())
}