#!/usr/bin/env perl
use strict;
use warnings;

my $os = `uname -s`;
chomp $os;
my $is_macos = ($os eq 'Darwin');
my $is_linux = ($os eq 'Linux');

# Helper to run command and strip newline
sub run_cmd {
    my $cmd = shift;
    my $output = `$cmd`;
    chomp $output;
    return $output;
}

# Print a section header
sub print_section {
    my $title = shift;
    print "\n=== $title ===\n";
}

# Collect information
print_section "System Information";
print "OS: $os\n";

my $os_version;
if ($is_macos) {
    $os_version = run_cmd('sw_vers -productVersion');
} elsif ($is_linux) {
    # Try to read /etc/os-release for pretty name
    if (-f '/etc/os-release') {
        my $release = run_cmd('grep PRETTY_NAME /etc/os-release | head -n1');
        # Remove surrounding quotes
        $release =~ s/.*"([^"]*)".*/$1/;
        $os_version = $release;
    }
}
print "OS Version: $os_version\n";

print "Kernel: " . run_cmd('uname -r') . "\n";

print_section "CPU";
my $cpu;
if ($is_macos) {
    $cpu = run_cmd('sysctl -n machdep.cpu.brand_string');
} elsif ($is_linux) {
    $cpu = run_cmd('grep "model name" /proc/cpuinfo | head -n1 | cut -d: -f2 | sed "s/^[ \t]*//"');
    $cpu =~ s/^[ \t]*//; $cpu =~ s/[ \t]*$//;
}
print "CPU: $cpu\n";

print_section "Memory";
if ($is_macos) {
    # macOS: use sysctl for total memory and vm_stat for pages
    my $mem_total_bytes = run_cmd('sysctl -n hw.memsize');
    my $mem_total_kb = $mem_total_bytes / 1024;
    my $vm_stats = run_cmd('vm_stat');
    my $free_pages = 0;
    my $inactive_pages = 0;
    my $speculative_pages = 0;
    if ($vm_stats =~ /Pages free:\s+(\d+)/) {
        $free_pages = $1;
    }
    if ($vm_stats =~ /Pages inactive:\s+(\d+)/) {
        $inactive_pages = $1;
    }
    if ($vm_stats =~ /Pages speculative:\s+(\d+)/) {
        $speculative_pages = $1;
    }
    my $page_size = run_cmd('sysctl -n hw.pagesize');
    my $free_mb = $free_pages * $page_size / (1024*1024);
    my $used_mb = ($mem_total_bytes / (1024*1024)) - $free_mb;
    print "Total Memory: " . int($mem_total_kb) . " KB\n";
    print "Free Memory (approx): " . sprintf("%.2f", $free_mb) . " MB\n";
    print "Used Memory (approx): " . sprintf("%.2f", $used_mb) . " MB\n";
} else {
    # Linux: use free -h for human readable
    my $free_output = run_cmd('free -h');
    print "$free_output\n";
}

print_section "Load Averages and Uptime";
my $uptime_output = run_cmd('uptime');
print "Uptime info: $uptime_output\n";

print_section "Disk Usage";
print run_cmd('df -h') . "\n";

print_section "Network Interfaces";
if ($is_macos) {
    print run_cmd('ifconfig') . "\n";
} else {
    print run_cmd('ip addr show') . "\n";
}

print_section "Logged-in Users";
print run_cmd('who') . "\n";