// https://tools.ietf.org/rfc/rfc5128.txt
// https://blog.csdn.net/bytxl/article/details/44344855

use flexi_logger::*;
use hbb_common::{bail, config::RENDEZVOUS_PORT, ResultType};
use hbbs::{common::*, *};

const RMEM: usize = 0;

fn main() -> ResultType<()> {
    let _logger = Logger::try_with_env_or_str("info")?
        .log_to_stdout()
        .format(opt_format)
        .write_mode(WriteMode::Async)
        .start()?;
    let args = format!(
        "-c --config=[FILE] +takes_value 'Sets a custom config file'
        -p, --port=[NUMBER(default={RENDEZVOUS_PORT})] 'Sets the listening port'
        -s, --serial=[NUMBER(default=0)] 'Sets configure update serial number'
        -R, --rendezvous-servers=[HOSTS] 'Sets rendezvous servers, separated by comma'
        -u, --software-url=[URL] 'Sets download url of RustDesk software of newest version'
        -r, --relay-servers=[HOST] 'Sets the default relay servers, separated by comma'
        -M, --rmem=[NUMBER(default={RMEM})] 'Sets UDP recv buffer size, set system rmem_max first, e.g., sudo sysctl -w net.core.rmem_max=52428800. vi /etc/sysctl.conf, net.core.rmem_max=52428800, sudo sysctl –p'
        --http-port=[NUMBER(default=21114)] 'HTTP management API port (0 disables)'
        --http-listen=[HOST] 'Bind address for --http-port. Default = wildcard. Set to 127.0.0.1 (or ::1) when nginx/Caddy fronts this port for TLS.'
        --ws-listen=[HOST] 'Bind address for the browser-facing WebSocket rendezvous port (port+2). Default = wildcard. Set to 127.0.0.1 (or ::1) when a reverse proxy claims the public port for TLS termination.'
        --bootstrap-admin-username=[USERNAME] 'Username to seed on first startup if users table is empty'
        --bootstrap-admin-password=[PASSWORD] 'Password to seed on first startup if users table is empty'
        --ab-legacy-mode=[on|off] 'When on, /api/ab/personal returns 404 to force legacy single-blob AB'
        --ab-max-peers-per-book=[NUMBER(default=100)] 'Surfaced via /api/ab/settings.max_peer_one_ab'
        --recording-dir=[PATH(default=./recordings)] 'Root directory for /api/record uploads'
        --recording-max-size-mb=[NUMBER] 'Optional ceiling per recording file; 0 or unset = unlimited'
        --audit-retention-days=[NUMBER] 'Hourly task deletes audit rows older than N days; 0 disables'
        --smtp-host=[HOST] 'SMTP host for email-code login; if empty, codes are logged to stdout (dev mode)'
        --smtp-port=[NUMBER(default=587)] 'SMTP port'
        --smtp-user=[USER] 'SMTP username (omit for unauthenticated relays)'
        --smtp-pass=[PASS] 'SMTP password'
        --smtp-from=[ADDR] 'From: address for outbound login emails (default: noreply@<smtp-host>)'
        --smtp-tls=[on|off] 'STARTTLS on the SMTP connection (default: on)'
        --public-base-url=[URL] 'Externally reachable HTTP base URL (e.g. https://rustdesk.example.com:21114) — required for OIDC redirect callbacks'
        --oidc-config=[PATH] 'TOML file describing OIDC providers (upserted into oidc_providers at startup)'
        --admin-ui-dir=[PATH] 'Directory of static admin-dashboard files served at /admin/ (default: ./admin_ui; empty disables)'
        , --mask=[MASK] 'Determine if the connection comes from LAN, e.g. 192.168.0.0/16'
        -k, --key=[KEY] 'Only allow the client with the same key'",
    );
    init_args(&args, "hbbs", "RustDesk ID/Rendezvous Server");
    let port = get_arg_or("port", RENDEZVOUS_PORT.to_string()).parse::<i32>()?;
    if port < 3 {
        bail!("Invalid port");
    }
    let rmem = get_arg("rmem").parse::<usize>().unwrap_or(RMEM);
    let serial: i32 = get_arg("serial").parse().unwrap_or(0);
    let http_port: i32 = get_arg_or("http-port", "21114".to_string())
        .parse()
        .unwrap_or(21114);
    crate::common::check_software_update();
    RendezvousServer::start(
        port,
        serial,
        &get_arg_or("key", "-".to_owned()),
        rmem,
        http_port,
        &get_arg("ws-listen"),
        &get_arg("http-listen"),
    )?;
    Ok(())
}
