mod args;
mod demo;
mod gateway;
mod serve;
mod sidecar;

use args::{is_help, print_usage};
use gateway::{
    DEFAULT_MIDDLEWARE_REPORT_PATH, DEFAULT_RESOURCE_REPORT_PATH, DEFAULT_RUNTIME_REPORT_PATH,
    DEFAULT_STATUS_BIND_ADDR, DEFAULT_STATUS_REPORT_PATH,
};
use serve::serve_gateway;
use sidecar::run_sidecar;

fn main() {
    if let Err(err) = run() {
        eprintln!("error: {err}");
        std::process::exit(1);
    }
}

fn run() -> Result<(), String> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.is_empty() || is_help(&args[0]) {
        print_usage(
            DEFAULT_STATUS_BIND_ADDR,
            DEFAULT_STATUS_REPORT_PATH,
            DEFAULT_RUNTIME_REPORT_PATH,
            DEFAULT_MIDDLEWARE_REPORT_PATH,
            DEFAULT_RESOURCE_REPORT_PATH,
        );
        return Ok(());
    }

    match args[0].as_str() {
        "gateway" | "serve-gateway" => serve_gateway(&args[1..]),
        "sidecar" | "gateway-sidecar" => run_sidecar(&args[1..]),
        "help" => {
            print_usage(
                DEFAULT_STATUS_BIND_ADDR,
                DEFAULT_STATUS_REPORT_PATH,
                DEFAULT_RUNTIME_REPORT_PATH,
                DEFAULT_MIDDLEWARE_REPORT_PATH,
                DEFAULT_RESOURCE_REPORT_PATH,
            );
            Ok(())
        }
        _ => {
            print_usage(
                DEFAULT_STATUS_BIND_ADDR,
                DEFAULT_STATUS_REPORT_PATH,
                DEFAULT_RUNTIME_REPORT_PATH,
                DEFAULT_MIDDLEWARE_REPORT_PATH,
                DEFAULT_RESOURCE_REPORT_PATH,
            );
            Err(format!("unsupported command: {}", args[0]))
        }
    }
}
