import Foundation func runCommandLine(_ arguments: [String]) { do { if arguments.contains("--help") { print("EzServerMac [--headless | --php | --import-library /absolute/path | --show-token]") return } if arguments == ["--php"] { try launchBundledPHP() return } guard arguments.isEmpty || arguments == ["--headless"] || arguments == ["--show-token"] || (arguments.count == 2 && arguments.first == "--import-library") else { throw CommandError.invalidArguments } let configuration = try ServerConfiguration() if arguments == ["--show-token"] { print(configuration.token) return } if arguments.count == 2 { let path = arguments[1] guard path.hasPrefix("/") else { throw CommandError.invalidArguments } let imported = try configuration.store.importLibrary(URL(fileURLWithPath: path, isDirectory: true)) print("Imported new patients: \(imported)") return } if let library = ProcessInfo.processInfo.environment["EZSERVER_LIBRARY"] { guard library.hasPrefix("/") else { throw CommandError.invalidArguments } let imported = try configuration.store.importLibrary(URL(fileURLWithPath: library, isDirectory: true)) print("Imported new patients: \(imported)") } let server = try LocalServer(port: configuration.port, configuration: configuration) server.start { state in switch state { case let .success(port): print("EzServer Mac is listening on http://0.0.0.0:\(port)") fflush(stdout) case let .failure(error): FileHandle.standardError.write(Data("Could not start EzServer: \(error.localizedDescription)\n".utf8)) exit(EXIT_FAILURE) } } withExtendedLifetime(server) { dispatchMain() } } catch { FileHandle.standardError.write(Data("EzServer: \(error.localizedDescription)\n".utf8)) exit(EXIT_FAILURE) } } private func launchBundledPHP() throws { guard let script = Bundle.main.resourceURL?.appendingPathComponent("php/run.sh"), FileManager.default.isReadableFile(atPath: script.path) else { throw CommandError.phpNotBundled } var arguments = [strdup("/bin/bash"), strdup(script.path), nil] defer { arguments.forEach { free($0) } } // Replace the launcher so the shell receives the caller's stop signals directly. _ = execv("/bin/bash", &arguments) throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } private enum CommandError: LocalizedError { case invalidArguments, phpNotBundled var errorDescription: String? { switch self { case .invalidArguments: return "Invalid arguments. Run EzServerMac --help." case .phpNotBundled: return "Original PHP is missing from this build. Prepare the runtime before building." } } }