import Foundation import ServiceManagement class AutostartManager { static let shared = AutostartManager() private let launchAgentURL: URL private let bundleIdentifier = "com.june.Haven" init() { let libraryDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first! let launchAgentsDir = libraryDir.appendingPathComponent("LaunchAgents") // Ensure directory exists try? FileManager.default.createDirectory(at: launchAgentsDir, withIntermediateDirectories: true) self.launchAgentURL = launchAgentsDir.appendingPathComponent("\(bundleIdentifier).plist") } var isEnabled: Bool { get { return FileManager.default.fileExists(atPath: launchAgentURL.path) } set { if newValue { enable() } else { disable() } } } private func enable() { guard !isEnabled else { return } // Point to the actual executable inside the bundle guard let appPath = Bundle.main.executablePath else { return } let plistContent: [String: Any] = [ "Label": bundleIdentifier, "ProgramArguments": [appPath], "RunAtLoad": true, "ProcessType": "Interactive" ] do { let data = try PropertyListSerialization.data(fromPropertyList: plistContent, format: .xml, options: 0) try data.write(to: launchAgentURL) } catch { print("Failed to enable autostart: \(error)") } } private func disable() { guard isEnabled else { return } do { try FileManager.default.removeItem(at: launchAgentURL) } catch { print("Failed to disable autostart: \(error)") } } }