AutostartManager.swift

1.9 KB · raw

1import Foundation2import ServiceManagement34class AutostartManager {5    static let shared = AutostartManager()6    7    private let launchAgentURL: URL8    private let bundleIdentifier = "com.june.Haven"9    10    init() {11        let libraryDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!12        let launchAgentsDir = libraryDir.appendingPathComponent("LaunchAgents")13        14        // Ensure directory exists15        try? FileManager.default.createDirectory(at: launchAgentsDir, withIntermediateDirectories: true)16        17        self.launchAgentURL = launchAgentsDir.appendingPathComponent("\(bundleIdentifier).plist")18    }19    20    var isEnabled: Bool {21        get {22            return FileManager.default.fileExists(atPath: launchAgentURL.path)23        }24        set {25            if newValue {26                enable()27            } else {28                disable()29            }30        }31    }32    33    private func enable() {34        guard !isEnabled else { return }35        36        // Point to the actual executable inside the bundle37        guard let appPath = Bundle.main.executablePath else { return }38        39        let plistContent: [String: Any] = [40            "Label": bundleIdentifier,41            "ProgramArguments": [appPath],42            "RunAtLoad": true,43            "ProcessType": "Interactive"44        ]45        46        do {47            let data = try PropertyListSerialization.data(fromPropertyList: plistContent, format: .xml, options: 0)48            try data.write(to: launchAgentURL)49        } catch {50            print("Failed to enable autostart: \(error)")51        }52    }53    54    private func disable() {55        guard isEnabled else { return }56        57        do {58            try FileManager.default.removeItem(at: launchAgentURL)59        } catch {60            print("Failed to disable autostart: \(error)")61        }62    }63}