Files
ezServer-MacOS/Sources/EzServerMac/CommandLine.swift
T

55 lines
2.2 KiB
Swift

import Foundation
func runCommandLine(_ arguments: [String]) {
do {
if arguments.contains("--help") {
print("EzServerMac [--headless | --import-library /absolute/path | --show-token]")
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 api = LibraryAPI(store: configuration.store, secret: configuration.token)
let server = try LocalServer(port: configuration.port, library: api)
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 enum CommandError: LocalizedError {
case invalidArguments
var errorDescription: String? { "Invalid arguments. Run EzServerMac --help." }
}