#!/usr/bin/env perl
# sysop_info.pl - System Information Collector for Sysops
# Requirements: Perl 5.10+, Read-only, No Sudo

use strict;
use warnings;
use Getopt::Long;
use POSIX qw(strftime);
use File::Basename;

my $verbose = 0;
GetOptions("verbose|v" => \$verbose);

# --- Configuration & OS Detection ---

my $os_type = $^O;
my $report_time = strftime("%Y-%m-%d %H:%M:%S", localtime);
my $hostname = `hostname 2>/dev/null`;
chomp $hostname;

# Determine OS-specific commands
my ($free_cmd, $ps_cmd, $if_cmd, $uptime_cmd, $df_cmd);

if ($os_type eq 'darwin') {
    # macOS
    $free_cmd  = "top -l 1 -s 0 | grep PhysMem";
    $ps_cmd    = "ps aux --sort=-%cpu | head -11"; # BSD ps
    $if_cmd    = "ifconfig";
    $uptime_cmd = "uptime";
    $df_cmd    = "df -h";
} elsif ($os_type eq 'linux') {
    # Linux
    $free_cmd  = "free -m";
    $ps_cmd    = "ps aux --sort=-%cpu | head -11";
    $if_cmd    = "ip addr";
    $uptime_cmd = "uptime";
    $df_cmd    = "df -h";
} else {
    die "Unsupported OS: $os_type\n";
}

# --- Data Collection Functions ---

sub print_header {
    print "=" x 60 . "\n";
    print "SYSOP INFO COLLECTOR\n";
    print "Time: $report_time\n";
    print "Host: $hostname\n";
    print "=" x 60 . "\n\n";
}

sub print_section {
    my ($title) = @_;
    print "-" x 60 . "\n";
    print " $title\n";
    print "-" x 60 . "\n";
}

sub get_kernel_version {
    my $ver = `uname -r 2>/dev/null`;
    chomp $ver;
    print "Kernel: $ver\n";
}

sub get_os_details {
    if ($os_type eq 'darwin') {
        my $sw_vers = `sw_vers 2>/dev/null`;
        print "\n$sw_vers";
    } elsif ($os_type eq 'linux') {
        my $os_release = `cat /etc/os-release 2>/dev/null`;
        if ($os_release) {
            print "\n$os_release";
        } else {
            print "\n(Linux distribution info not found in /etc/os-release)\n";
        }
    }
}

sub get_uptime_and_load {
    print_section("UPTIME & LOAD");
    my $uptime = `$uptime_cmd 2>/dev/null`;
    print "\n$uptime" if $uptime;
}

sub get_memory {
    print_section("MEMORY");
    my $mem = `$free_cmd 2>/dev/null`;
    print "\n$mem" if $mem;
}

sub get_disk_usage {
    print_section("DISK USAGE");
    my $disk = `$df_cmd 2>/dev/null`;
    print "\n$disk" if $disk;
}

sub get_network {
    print_section("NETWORK INTERFACES");
    my $net = `$if_cmd 2>/dev/null`;
    print "\n$net" if $net;
}

sub get_top_processes {
    print_section("TOP 10 PROCESSES (BY CPU)");
    my $procs = `$ps_cmd 2>/dev/null`;
    print "\n$procs" if $procs;
}

sub get_user_info {
    print_section("USER INFO");
    print "User: `whoami`\n";
    print "Groups: `id -Gn`\n";
    print "Shell: `echo \$SHELL`\n";
}

# --- Main Execution ---

print_header();
get_kernel_version();
get_os_details();
get_uptime_and_load();
get_memory();
get_disk_usage();
get_network();
get_top_processes();
get_user_info();

print "\n" . "=" x 60 . "\n";
print "END OF REPORT\n";
print "=" x 60 . "\n";
