#import <ObjFW/ObjFW.h>
#import <linux/sysctl.h>
#import <sys/time.h>
#import <sys/resource.h>
#import <unistd.h>

@interface Ruptime: OFObject
- (void)printUptimeAndLoad;
@end

@implementation Ruptime

// Helper function to get system uptime
- (NSString *)getUptime
{
    struct timeval boottime;
    size_t size = sizeof(boottime);
    int mib[2] = {CTL_KERN, KERN_BOOTTIME};
    
    if (sysctl(mib, 2, &boottime, &size, NULL, 0) < 0) {
        return @"Error retrieving uptime";
    }
    
    time_t bsec = boottime.tv_sec;
    time_t current_time = time(NULL);
    
    int uptime_sec = (int)difftime(current_time, bsec);
    int days = uptime_sec / (60 * 60 * 24);
    int hours = (uptime_sec % (60 * 60 * 24)) / (60 * 60);
    int minutes = (uptime_sec % (60 * 60)) / 60;
    
    return [OFString stringWithFormat: @"Uptime: %d days, %d hours, %d minutes", days, hours, minutes];
}

// Helper function to get load averages
- (NSString *)getLoadAverage
{
    double loadavg[3];
    
    if (getloadavg(loadavg, 3) == -1) {
        return @"Error retrieving load averages";
    }
    
    return [OFString stringWithFormat: @"Load Averages: %.2f, %.2f, %.2f", loadavg[0], loadavg[1], loadavg[2]];
}

- (void)printUptimeAndLoad
{
    NSString *uptime = [self getUptime];
    NSString *loadAvg = [self getLoadAverage];
    
    OFLog(@"%@\n%@", uptime, loadAvg);
}

@end

int main(int argc, const char *argv[])
{
    @autoreleasepool {
        Ruptime *ruptime = [Ruptime new];
        [ruptime printUptimeAndLoad];
    }
    return 0;
}
