#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(uname);

# Determine OS type
my $os = uname();
my $is_macos = ($os eq 'Darwin');
my $is_linux = ($os eq 'Linux');

print "System Information Report\n";
print "=" x 50 . "\n\n";

# OS Information
print "OS Information:\n";
print "  OS Type: $os\n";
if ($is_macos) {
    my $version = `sw_vers -productVersion`;
    chomp $version;
    print "  macOS Version: $version\n";
} elsif ($is_linux) {
    my $distro = `lsb_release -d 2>/dev/null || cat /etc/os-release 2>/dev/null | grep PRETTY_NAME`;
    chomp $distro;
    $distro =~ s/^.*PRETTY_NAME="// if $distro;
    $distro =~ s/"$//;
    print "  Distribution: $distro\n";
}
print "  Kernel: " . uname() . "\n";
my $hostname = `hostname -s 2>/dev/null || hostname`;
chomp $hostname;
print "  Hostname: $hostname\n";
print "\n";

# CPU Information
print "CPU Information:\n";
my $cpu_info = `sysctl -n machdep.cpu.brand_string 2>/dev/null || lscpu 2>/dev/null | grep "Model name"`;
chomp $cpu_info;
if ($cpu_info) {
    $cpu_info =~ s/^.*: //;
    print "  Model: $cpu_info\n";
}
my $cpu_cores = `sysctl -n hw.physicalcpu 2>/dev/null || nproc --all`;
chomp $cpu_cores;
print "  Physical Cores: $cpu_cores\n";
print "\n";

# Memory Information
print "Memory Information:\n";
my $mem_total = `sysctl -n hw.memsize 2>/dev/null || cat /proc/meminfo | grep MemTotal`;
chomp $mem_total;
if ($mem_total =~ /(\d+)/) {
    my $bytes = $1;
    my $gb = sprintf("%.2f", $bytes / (1024**3)) if $bytes >= 1024**3;
    my $mb = sprintf("%.2f", $bytes / (1024**2)) if $bytes < 1024**3 && $bytes >= 1024**2;
    print "  Total: " . ($gb // $mb // $bytes) . ($gb ? " GB" : $mb ? " MB" : " bytes") . "\n";
}
print "\n";

# Disk Information
print "Disk Information:\n";
my $disk_info = `df -h / 2>/dev/null | tail -1`;
chomp $disk_info;
if ($disk_info) {
    my @fields = split /\s+/, $disk_info;
    print "  Root Partition: $fields[0]\n";
    print "  Size: $fields[1]\n";
    print "  Used: $fields[2]\n";
    print "  Available: $fields[3]\n";
    print "  Usage: $fields[4]\n";
}
print "\n";

# System Load
print "System Load:\n";
my $load_avg = `uptime`;
chomp $load_avg;
print "  $load_avg\n";
print "\n";

# Uptime
print "Uptime:\n";
my $uptime = `uptime`;
chomp $uptime;
$uptime =~ s/.*up (.+?), .*/$1/;
print "  $uptime\n";
print "\n";

# Network Information
print "Network Information:\n";
my $interfaces = `ifconfig -a 2>/dev/null | grep "^[a-z]" | awk '{print $1}' | head -5`;
if ($interfaces) {
    $interfaces =~ s/\n/\n  /g;
    print "  Active Interfaces:\n  $interfaces\n";
} else {
    print "  Active Interfaces: N/A\n";
}
print "\n";

# Running Processes
print "Running Processes:\n";
my $process_count = `ps aux | wc -l`;
chomp $process_count;
$process_count--; # Subtract header line
print "  Total Processes: $process_count\n";
print "\n";

print "End of Report\n";
