//
// www.ubugtrack.com - Crash Reporter for iOS and macOS (Swift), version 1
// Sends the crashes of an app (Swift or Objective-C; iOS 13+, macOS 10.15+, tvOS 13+, visionOS 1+)
// to the Crash Reporter of a uBugtrack project. One file, no dependency.
//
// It reports:
//   - the uncaught Objective-C exceptions (NSInvalidArgumentException, NSRangeException...),
//   - the crash signals: SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGABRT, and SIGTRAP, which is how Swift
//     stops on fatalError(), a force unwrap of nil, an index out of range, try!...
//
// Add this file to the app, then call start() once, as early as possible:
//     SwiftUI:  init() { UbugtrackCrashReporter.start(crashKey: "YOUR_CRASH_KEY") }  (in your App)
//     UIKit:    UbugtrackCrashReporter.start(crashKey: "YOUR_CRASH_KEY") in application(_:didFinishLaunchingWithOptions:)
//     AppKit:   the same, in applicationWillFinishLaunching(_:)
//
// The crash is saved to a file when it happens (no network: the app is dying), and sent at the next
// launch of the app. Then the app ends as usual: the system crash report (Xcode Organizer, App Store
// Connect), the debugger and the other crash reporters still see the crash.
//
// Good to know:
//   - Release builds strip the symbols of the app: its frames read "MyApp + 12345" (offset in the app).
//     Set "Strip Style" to "Debugging Symbols" in the build settings to keep the function names.
//   - macOS: AppKit catches the exceptions of the main thread, unless NSApplicationCrashOnExceptions is set.
//   - A stack overflow (endless recursion) is not reported.
//

import Darwin
import Foundation
import MachO

public enum UbugtrackCrashReporter {

    private static let defaultEndpoint = URL(string: "https://ubugtrack.com/crashdump.php")!
    private static let folderName = "ubugtrack_crashes"
    private static let maxPending = 5
    private static let timeout: TimeInterval = 10
    private static let logMax = 2047 // the server keeps 2047 bytes of the log

    private static let lock = NSLock()
    nonisolated(unsafe) private static var started = false

    /// Call it once, as early as possible (App init, application(_:didFinishLaunchingWithOptions:)).
    /// - version: the app version to report. By default "CFBundleShortVersionString (CFBundleVersion)".
    /// - endpoint: only to send to another uBugtrack server (tests).
    public static func start(crashKey: String, version: String? = nil, endpoint: URL? = nil) {
        lock.lock()
        defer { lock.unlock() }
        if started {
            return
        }
        started = true

        let endpoint = endpoint ?? defaultEndpoint
        guard let folder = crashFolder() else {
            return
        }

        // The file of this launch: the crash handlers write into it. Locked while the app runs.
        let name = String(format: "%014.0f-%d.crash", Date().timeIntervalSince1970 * 1000, getpid())
        let file = open(folder.appendingPathComponent(name).path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0o600)
        if file >= 0 {
            if flock(file, LOCK_EX | LOCK_NB) == 0 {
                // Saved now: the app may be updated before the next launch
                writeText(file, "ubugtrack 1\nappversion \(oneLine(version ?? bundleVersion()))\nmanufacturer \(hardwareModel())\nmodel \(systemName())\n")
                installHandlers(file: file)
            } else {
                close(file)
            }
        }

        DispatchQueue.global(qos: .utility).async {
            sendPending(in: folder, current: name, crashKey: crashKey, endpoint: endpoint)
        }
    }

    //*********************************************************************
    // Crash handlers

    private static func installHandlers(file: Int32) {
        // Everything the signal handler needs is ready before it is installed
        crashFrames = UnsafeMutablePointer<UnsafeMutableRawPointer?>.allocate(capacity: Int(maxFrames))
        crashFrames?.initialize(repeating: nil, count: Int(maxFrames))
        crashScratch = UnsafeMutablePointer<UInt8>.allocate(capacity: scratchSize)
        crashAnnotations = swiftCrashInfo()
        previousActions = UnsafeMutablePointer<sigaction>.allocate(capacity: 32)
        previousActions?.initialize(repeating: sigaction(), count: 32)
        crashFile = file

        previousExceptionHandler = NSGetUncaughtExceptionHandler()
        NSSetUncaughtExceptionHandler(handleException)

        var action = sigaction()
        action.__sigaction_u.__sa_sigaction = handleSignal
        action.sa_flags = SA_SIGINFO
        sigemptyset(&action.sa_mask)
        for signal in [SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP] {
            if let previous = previousActions {
                sigaction(signal, &action, previous + Int(signal))
            }
        }
    }

    // The crash annotations of the Swift runtime: it puts its message there ("Fatal error: ...")
    private static func swiftCrashInfo() -> UnsafeRawPointer? {
        var info = Dl_info()
        guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "swift_retain"), // RTLD_DEFAULT
              dladdr(symbol, &info) != 0, let base = info.dli_fbase else {
            return nil
        }
        var size: UInt = 0
        guard let section = getsectiondata(base.assumingMemoryBound(to: mach_header_64.self), "__DATA", "__crash_info", &size),
              size >= 16 else {
            return nil
        }
        return UnsafeRawPointer(section)
    }

    //*********************************************************************
    // Crashes not sent yet: sent at the next launch, deleted once sent

    private static func crashFolder() -> URL? {
        guard let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
            return nil
        }
        // macOS: Application Support is shared by the apps that are not sandboxed
        let owner = Bundle.main.bundleIdentifier ?? ProcessInfo.processInfo.processName
        var folder = support.appendingPathComponent(owner, isDirectory: true).appendingPathComponent(folderName, isDirectory: true)
        do {
            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
        } catch {
            return nil
        }
        var values = URLResourceValues()
        values.isExcludedFromBackup = true
        try? folder.setResourceValues(values)
        return folder
    }

    private static func sendPending(in folder: URL, current: String, crashKey: String, endpoint: URL) {
        let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
        var crashes: [(path: String, file: Int32, body: String)] = []
        for name in names.sorted() where name.hasSuffix(".crash") && name != current {
            let path = folder.appendingPathComponent(name).path
            let file = open(path, O_RDONLY | O_CLOEXEC)
            if file < 0 {
                continue
            }
            // Locked: the file of an app that is still running. Kept locked until it is sent.
            if flock(file, LOCK_EX | LOCK_NB) != 0 {
                close(file)
                continue
            }
            var status = stat()
            let date = fstat(file, &status) == 0 ? Date(timeIntervalSince1970: TimeInterval(status.st_mtimespec.tv_sec)) : Date()
            let text = FileManager.default.contents(atPath: path).map { String(decoding: $0, as: UTF8.self) } ?? ""
            if let fields = report(text, date: date) {
                crashes.append((path, file, formBody([("project_key", crashKey)] + fields)))
            } else {
                // That launch did not crash
                unlink(path)
                close(file)
            }
        }

        // Only the last ones
        while crashes.count > maxPending {
            let oldest = crashes.removeFirst()
            unlink(oldest.path)
            close(oldest.file)
        }
        if crashes.isEmpty {
            return
        }

        let configuration = URLSessionConfiguration.ephemeral
        configuration.timeoutIntervalForRequest = timeout
        configuration.timeoutIntervalForResource = timeout
        let session = URLSession(configuration: configuration)
        for crash in crashes {
            var request = URLRequest(url: endpoint, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
            request.httpMethod = "POST"
            request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
            request.httpBody = Data(crash.body.utf8)
            let path = crash.path
            let file = crash.file
            session.dataTask(with: request) { _, response, _ in
                // Not sent: it is sent again at the next launch
                if let code = (response as? HTTPURLResponse)?.statusCode, code >= 200 && code < 300 {
                    unlink(path)
                }
                close(file)
            }.resume()
        }
        session.finishTasksAndInvalidate()
    }

    //*********************************************************************
    // Report: the fields of the server, from a crash file

    private static func report(_ text: String, date: Date) -> [(String, String)]? {
        var values: [String: String] = [:]
        var frames: [String] = []
        var inFrames = false
        for line in text.split(separator: "\n") {
            if inFrames {
                frames.append(String(line))
            } else if line == "frames" {
                inFrames = true
            } else {
                let parts = line.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)
                values[String(parts[0])] = parts.count > 1 ? String(parts[1]) : ""
            }
        }

        var title: String
        var lines: [String] = []
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'UTC'"
        lines.append("Date: " + formatter.string(from: date))

        if let signal = values["signal"] {
            // The first frames are the signal handler, up to _sigtramp
            var parsed = frames.compactMap(parseFrame)
            if let sigtramp = parsed.firstIndex(where: { $0.symbol.hasPrefix("_sigtramp ") }) {
                parsed.removeFirst(sigtramp + 1)
            }

            // One title per bug (uBugtrack groups crashes by title):
            // "SIGTRAP: Fatal error: Index out of range in CartView.total()", "SIGSEGV in CheckoutModel.pay()"
            title = signal
            if let message = values["message"]?.trimmingCharacters(in: .whitespaces), !message.isEmpty {
                lines.append(message)
                title += ": " + replacing("^[^ :][^:]*:\\d+: ", in: message, with: "") // no "File.swift:12: "
            }
            if let symbol = appSymbol(parsed) {
                title += " in " + symbol
            }
            title = String(title.prefix(200))

            if let address = values["address"], let value = UInt64(address.dropFirst(2), radix: 16) {
                lines.append("Bad access at 0x" + String(value, radix: 16))
            }
            lines.append(values["thread"] == "main" ? "Thread 0 Crashed:" : "Crashed Thread (not the main thread):")
            frames = format(parsed)
        } else if let name = values["name"], values["exception"] != nil {
            let reason = values["reason"] ?? ""
            title = reason.isEmpty ? name : name + ": " + reason
            lines.append("Last Exception Backtrace:")
            frames = format(frames.compactMap(parseFrame))
        } else {
            return nil
        }
        if title.count > 1000 {
            title = String(title.prefix(1000))
        }

        // Whole lines only: the frames that do not fit are counted
        var log = lines.joined(separator: "\n")
        for (index, frame) in frames.enumerated() {
            let more = "\n... \(frames.count - index) more"
            if log.utf8.count + 1 + frame.utf8.count + (index < frames.count - 1 ? more.utf8.count : 0) > logMax {
                log += more
                break
            }
            log += "\n" + frame
        }

        return [("logtitle", title),
                ("logfull", log),
                ("manufacturer", values["manufacturer"] ?? hardwareModel()),
                ("model", values["model"] ?? systemName()),
                ("appversion", values["appversion"] ?? bundleVersion())]
    }

    // "3   My App   0x0000000102e1c3a0 $s5MyApp4mainyyF + 48" (backtrace_symbols, callStackSymbols)
    private static let framePattern = try? NSRegularExpression(pattern: "^\\d+\\s+(.+?)\\s+0x([0-9a-fA-F]+)\\s+(.*)$")

    private static func parseFrame(_ line: String) -> (module: String, address: String, symbol: String)? {
        let range = NSRange(line.startIndex..., in: line)
        guard let match = framePattern?.firstMatch(in: line, range: range), match.numberOfRanges == 4,
              let module = Range(match.range(at: 1), in: line),
              let address = Range(match.range(at: 2), in: line),
              let symbol = Range(match.range(at: 3), in: line) else {
            return nil
        }
        let value = UInt64(line[address], radix: 16) ?? 0
        return (String(line[module]), "0x" + String(value, radix: 16), String(line[symbol]))
    }

    // "0 My_App 0x102e1c3a0 MyApp.main() -> () + 48": one word for the module, Swift symbols demangled
    private static func format(_ frames: [(module: String, address: String, symbol: String)]) -> [String] {
        frames.enumerated().map { index, frame in
            let (name, offset) = splitOffset(frame.symbol)
            var symbol = demangle(name)
            if symbol.count > 200 {
                symbol = symbol.prefix(200) + "..."
            }
            return "\(index) \(frame.module.replacingOccurrences(of: " ", with: "_")) \(frame.address) \(symbol)\(offset)"
        }
    }

    // "MyApp.main() + 48" -> ("MyApp.main()", " + 48")
    private static func splitOffset(_ symbol: String) -> (String, String) {
        if let plus = symbol.range(of: " + ", options: .backwards), Int(symbol[plus.upperBound...]) != nil {
            return (String(symbol[..<plus.lowerBound]), String(symbol[plus.lowerBound...]))
        }
        return (symbol, "")
    }

    // "CheckoutModel.crash(String)": the first frame of the app, short. Nil when the app is stripped.
    private static func appSymbol(_ frames: [(module: String, address: String, symbol: String)]) -> String? {
        let executable = Bundle.main.executableURL?.lastPathComponent ?? ProcessInfo.processInfo.processName
        // Xcode debug builds put the code of the app in "MyApp.debug.dylib"
        guard let frame = frames.first(where: { $0.module == executable || $0.module == executable + ".debug.dylib" }) else {
            return nil
        }
        let mangled = splitOffset(frame.symbol).0
        if mangled.isEmpty || mangled == frame.module || mangled.hasPrefix("0x") {
            return nil
        }

        // "closure #1 @Sendable () -> () in MyApp.Cart.total(Swift.Int) -> Swift.Int" -> "closure #1 in Cart.total(Int)"
        var symbol = dropReturnTypes(demangle(mangled))
        symbol = replacing("(closure #\\d+)(?: @\\w+)*(?: \\(.*?\\))? in ", in: symbol, with: "$1 in ")
        if let module = swiftModule(mangled) {
            symbol = replacing("(^|[^\\w.])" + NSRegularExpression.escapedPattern(for: module) + "\\.", in: symbol, with: "$1")
        }
        symbol = replacing("(^|[^\\w.])Swift\\.", in: symbol, with: "$1")
        return String(symbol.prefix(80))
    }

    // " -> Swift.Int": up to " in ", the end, or the bracket that closes the parameters
    private static func dropReturnTypes(_ symbol: String) -> String {
        let characters = Array(symbol)
        var result = ""
        var index = 0
        while index < characters.count {
            guard String(characters[index..<min(index + 4, characters.count)]) == " -> " else {
                result.append(characters[index])
                index += 1
                continue
            }
            var depth = 0
            index += 4
            while index < characters.count {
                let character = characters[index]
                if character == "(" || character == "[" || character == "<" {
                    depth += 1
                } else if character == ")" || character == "]" || (character == ">" && characters[index - 1] != "-") {
                    if depth == 0 {
                        break
                    }
                    depth -= 1
                } else if depth == 0 && String(characters[index..<min(index + 4, characters.count)]) == " in " {
                    break
                }
                index += 1
            }
        }
        return result
    }

    // "$s9MyApp4CartV5totalSiyF" -> "MyApp"
    private static func swiftModule(_ mangled: String) -> String? {
        guard let start = ["_$s", "$s", "$S"].first(where: { mangled.hasPrefix($0) }) else {
            return nil
        }
        let rest = mangled.dropFirst(start.count)
        let digits = rest.prefix { $0 >= "0" && $0 <= "9" }
        guard let length = Int(digits), length > 0 else {
            return nil
        }
        let module = rest.dropFirst(digits.count).prefix(length)
        return module.count == length ? String(module) : nil
    }

    private static func replacing(_ pattern: String, in text: String, with template: String) -> String {
        guard let expression = try? NSRegularExpression(pattern: pattern) else {
            return text
        }
        return expression.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: template)
    }

    private typealias DemangleFunction = @convention(c) (UnsafePointer<CChar>?, Int, UnsafeMutablePointer<CChar>?, UnsafeMutablePointer<Int>?, UInt32) -> UnsafeMutablePointer<CChar>?

    private static func demangle(_ symbol: String) -> String {
        guard symbol.hasPrefix("$s") || symbol.hasPrefix("_$s") || symbol.hasPrefix("$S") || symbol.hasPrefix("_T0"),
              let function = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "swift_demangle") else {
            return symbol
        }
        let swiftDemangle = unsafeBitCast(function, to: DemangleFunction.self)
        guard let result = symbol.withCString({ swiftDemangle($0, strlen($0), nil, nil, 0) }) else {
            return symbol
        }
        defer { free(result) }
        return String(cString: result)
    }

    private static func formBody(_ fields: [(String, String)]) -> String {
        var allowed = CharacterSet()
        allowed.insert(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
        return fields.map { name, value in
            name + "=" + (value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")
        }.joined(separator: "&")
    }

    //*********************************************************************
    // App and device

    // "1.4 (27)"
    private static func bundleVersion() -> String {
        let info = Bundle.main.infoDictionary
        let short = info?["CFBundleShortVersionString"] as? String
        let build = info?["CFBundleVersion"] as? String
        switch (short, build) {
        case let (short?, build?): return short == build ? short : "\(short) (\(build))"
        case let (short?, nil): return short
        case let (nil, build?): return build
        default: return "unknown"
        }
    }

    // "iPhone17,1", "Mac16,1"
    private static func hardwareModel() -> String {
        #if targetEnvironment(simulator)
        if let model = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
            return model
        }
        #endif
        if let machine = sysctlString("hw.machine"), machine.contains(",") {
            return machine
        }
        // A Mac: hw.machine is "arm64"
        return sysctlString("hw.model") ?? "unknown"
    }

    // "iOS 26.1", "macOS 26.2"
    private static func systemName() -> String {
        #if os(macOS) || targetEnvironment(macCatalyst)
        let name = "macOS"
        #elseif os(tvOS)
        let name = "tvOS"
        #elseif os(visionOS)
        let name = "visionOS"
        #elseif os(watchOS)
        let name = "watchOS"
        #else
        let name = "iOS"
        #endif
        let version = ProcessInfo.processInfo.operatingSystemVersion
        let patch = version.patchVersion > 0 ? ".\(version.patchVersion)" : ""
        return "\(name) \(version.majorVersion).\(version.minorVersion)\(patch)"
    }

    private static func sysctlString(_ name: String) -> String? {
        var size = 0
        guard sysctlbyname(name, nil, &size, nil, 0) == 0, size > 0 else {
            return nil
        }
        var buffer = [UInt8](repeating: 0, count: size)
        guard sysctlbyname(name, &buffer, &size, nil, 0) == 0 else {
            return nil
        }
        return String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self)
    }

    private static func oneLine(_ text: String) -> String {
        text.components(separatedBy: .newlines).joined(separator: " ")
    }

    fileprivate static func writeText(_ file: Int32, _ text: String) {
        let bytes = Array(text.utf8)
        bytes.withUnsafeBytes { buffer in
            var offset = 0
            while offset < buffer.count, let base = buffer.baseAddress {
                let written = write(file, base + offset, buffer.count - offset)
                if written <= 0 {
                    break
                }
                offset += written
            }
        }
    }

    // Objective-C exceptions: not a signal handler, so Foundation can be used
    fileprivate static func writeException(_ exception: NSException) {
        var symbols = exception.callStackSymbols
        if symbols.isEmpty {
            symbols = Thread.callStackSymbols
        }
        writeText(crashFile, "exception\nname \(oneLine(exception.name.rawValue))\nreason \(oneLine(exception.reason ?? ""))\nframes\n"
            + symbols.joined(separator: "\n") + "\n")
    }
}

//*********************************************************************
// State of the crash handlers: set in start(), before they are installed.
// The signal handler only reads it, with async-signal-safe calls (no Swift string, array or allocation).

private let maxFrames: Int32 = 128
private let scratchSize = 1024
nonisolated(unsafe) private var crashFile: Int32 = -1
nonisolated(unsafe) private var crashWritten = false
nonisolated(unsafe) private var crashFrames: UnsafeMutablePointer<UnsafeMutableRawPointer?>? = nil
nonisolated(unsafe) private var crashScratch: UnsafeMutablePointer<UInt8>? = nil
nonisolated(unsafe) private var crashAnnotations: UnsafeRawPointer? = nil
nonisolated(unsafe) private var previousActions: UnsafeMutablePointer<sigaction>? = nil
nonisolated(unsafe) private var previousExceptionHandler: (@convention(c) (NSException) -> Void)? = nil

private func handleException(_ exception: NSException) {
    if !crashWritten && crashFile >= 0 {
        // The SIGABRT that follows is not written again
        crashWritten = true
        UbugtrackCrashReporter.writeException(exception)
    }
    previousExceptionHandler?(exception)
}

private func handleSignal(_ signal: Int32, _ info: UnsafeMutablePointer<__siginfo>?, _ context: UnsafeMutableRawPointer?) {
    if !crashWritten && crashFile >= 0 {
        crashWritten = true
        writeSignal(signal, info)
    }
    // The previous action, and the same signal again: the app ends as it would without this file
    if let previous = previousActions {
        sigaction(signal, previous + Int(signal), nil)
    }
    raise(signal)
}

private func writeSignal(_ signal: Int32, _ info: UnsafeMutablePointer<__siginfo>?) {
    switch signal {
    case SIGABRT: put("signal SIGABRT\n")
    case SIGBUS: put("signal SIGBUS\n")
    case SIGFPE: put("signal SIGFPE\n")
    case SIGILL: put("signal SIGILL\n")
    case SIGSEGV: put("signal SIGSEGV\n")
    case SIGTRAP: put("signal SIGTRAP\n")
    default: put("signal SIGNAL\n")
    }
    put(pthread_main_np() != 0 ? "thread main\n" : "thread other\n")
    if signal == SIGSEGV || signal == SIGBUS, let info = info {
        put("address ")
        putHex(UInt(bitPattern: info.pointee.si_addr))
        put("\n")
    }
    putSwiftMessage()
    put("frames\n")
    if let frames = crashFrames {
        let count = backtrace(frames, maxFrames)
        backtrace_symbols_fd(frames, count, crashFile)
    }
}

private func put(_ text: StaticString) {
    write(crashFile, text.utf8Start, text.utf8CodeUnitCount)
}

private func putHex(_ value: UInt) {
    guard let scratch = crashScratch else {
        return
    }
    scratch[0] = 48 // 0
    scratch[1] = 120 // x
    var rest = value
    var index = 17
    while index >= 2 {
        let digit = UInt8(truncatingIfNeeded: rest & 15)
        scratch[index] = digit < 10 ? 48 + digit : 87 + digit
        rest >>= 4
        index -= 1
    }
    write(crashFile, scratch, 18)
}

// "main.swift:12: Fatal error: Index out of range", on one line
private func putSwiftMessage() {
    guard let annotations = crashAnnotations, let scratch = crashScratch else {
        return
    }
    let address = annotations.load(fromByteOffset: 8, as: UInt.self)
    guard let message = UnsafePointer<UInt8>(bitPattern: address) else {
        return
    }
    var count = 0
    while count < scratchSize && message[count] != 0 {
        let byte = message[count]
        scratch[count] = byte == 10 || byte == 13 ? 32 : byte
        count += 1
    }
    put("message ")
    write(crashFile, scratch, count)
    put("\n")
}
