//
//  main.swift
//  cmdbar_updater
//
//  Created by Igor Kolokolnikov on 5/23/24.
//

import AppKit

fileprivate func existsAtPath(_ path: String, isDirectory: Bool = false) -> Bool {
    var isDirectory: ObjCBool = ObjCBool(isDirectory)
    let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
    return exists
}

let tmp = FileManager.default.temporaryDirectory.appending(path: "CmdBar.app")
let app = Bundle.main.bundleURL

if !existsAtPath(tmp.path(), isDirectory: true) { exit(1) }

do {
    let _ = try FileManager.default.replaceItemAt(app, withItemAt: tmp)
} catch {
    if existsAtPath(tmp.path(), isDirectory: true) {
        do { try FileManager.default.removeItem(at: tmp) } catch {}
    }
    exit(1)
}

let configuration = NSWorkspace.OpenConfiguration()
NSWorkspace.shared.openApplication(at: app, configuration: configuration, completionHandler: nil)

usleep(100000*2) // Allow 2 seconds to let `NSWorkspace.shared.openApplication` finish launching our app.
