//
//  kernel_find.m
//  TrollInstallerX
//
//  Created by Alfie on 19/03/2024.
//

#import <Foundation/Foundation.h>
#import <sys/mount.h>

// Credit to Dhinak G!
NSString *get_kernelcache_path(void) {
    int mntsize;
    struct statfs* mntbuf;
    mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
    for (int i = 0; i < mntsize; i++) {
        if (strcmp(mntbuf[i].f_mntonname, "/") == 0) {
            // We get something like com.apple.os.update-594579A7E6CFED557C556E7ABB1AD049D38880177508473C8DE7F877A3EA3889177409ECF379C8A23FD26B805F2E4F23@/dev/disk1s1
            // or com.apple.os.update-CA268AE621CD92A4AEBD8FCD349FCA0587864C1A@/dev/disk0s1s1
            // From this, we want only the UUID
            NSString* snapshotName = [NSString stringWithUTF8String:mntbuf[i].f_mntfromname];
            NSString* bootManifestHash = [snapshotName substringWithRange:NSMakeRange(20, [snapshotName rangeOfString:@"@"].location - 20)];
            NSLog(@"bootManifestHash: %@", bootManifestHash);
            NSString* kernelcachePath = [[@"/private/preboot" stringByAppendingPathComponent:bootManifestHash] stringByAppendingPathComponent:@"System/Library/Caches/com.apple.kernelcaches/kernelcache"];
            return kernelcachePath;
        }
    }
    return nil;
}
