using CommandLine; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using RedisManager.Commands; using Crayon; namespace RedisManager { /// /// Main entry point for the RedisManager application. /// Supports service (daemon) mode and client mode only. /// class Program { /// /// Main entry point that determines the operational mode based on command line arguments. /// /// Command line arguments /// Exit code (0 for success, non-zero for errors) static async Task Main(string[] args) { // No arguments: run as a daemon (service mode) // Service mode: allow optional --config if (args.Length == 0 || (args.Length >= 2 && args[0] == "--config")) { string configPath = null; if (args.Length >= 2 && args[0] == "--config") { configPath = args[1]; // Remove --config and path from args for service mode args = args.Skip(2).ToArray(); } return await RunServiceMode(); } // Standalone mode removed: all commands require daemon/service. // With arguments: try to connect to the daemon (client mode) var client = new RedisManagerClient(); var clientResult = await client.ExecuteCommandAsync(args); // A specific exit code (2) from the client indicates the service is not running if (clientResult == 2) { // Allow help output even if no daemon and no --instance bool wantsHelp = args.Any(arg => arg == "help" || arg == "--help" || arg == "-h"); if (!wantsHelp) { Console.WriteLine(Output.Red("Error: RedisManager daemon/service is not running. Please start the service (no arguments) and retry your command.")); } } // Return the result from the client (0 for success, 1 for other errors) return clientResult; } /// /// Runs RedisManager in service mode, starting a TCP server that accepts client connections. /// The service runs indefinitely until interrupted by Ctrl+C or other termination signals. /// /// Exit code (0 for successful shutdown) static async Task RunServiceMode() { Console.WriteLine("Starting RedisManager Service..."); var service = new RedisManagerService(); await service.StartAsync(); // Block the main thread until Ctrl+C is pressed var cts = new System.Threading.CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cts.Cancel(); }; Console.WriteLine("RedisManager daemon is running. Press Ctrl+C to exit."); try { await Task.Delay(-1, cts.Token); } catch (OperationCanceledException) { Console.WriteLine("Shutting down RedisManager Service..."); } await service.StopAsync(); return 0; } } }