// file: kb_demo_app/src/main.rs

// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

//! Binary entrypoint for the kb application.
//!
//! This binary remains intentionally thin and delegates its logic to `kb_lib`.

#![deny(unreachable_pub)]
#![warn(missing_docs)]

use fs2::FileExt;

/// Entrypoint of the kb app binary.
#[tokio::main]
async fn main() -> std::process::ExitCode {
    let mut lock_path = std::env::temp_dir();
    lock_path.push("com_khadhroony_solana_rust.lock");
    let lock_file = match std::fs::File::create(lock_path) {
        Ok(lock) => lock,
        Err(_err) => {
            eprintln!("Cannot create lock!");
            std::process::exit(1);
        },
    };
    // trying to aquire an exclusive lock
    if lock_file.try_lock_exclusive().is_err() {
        eprintln!("Another instance of the app is already running!");
        std::process::exit(1);
    }
    if rustls::crypto::CryptoProvider::get_default().is_none() {
        let provider_result = rustls::crypto::aws_lc_rs::default_provider().install_default();
        match provider_result {
            Ok(()) => {},
            Err(error) => {
                eprintln!("kb_demo_app rustls provider init error: {:?}", error);
                return std::process::ExitCode::FAILURE;
            },
        }
    }
    let run_result = kb_demo_app_lib::run().await;
    if let Err(error) = run_result {
        eprintln!("application error: {}", error);
        std::process::exit(1);
    }
    std::process::ExitCode::SUCCESS
}
