#!/usr/bin/perl

=head1 NAME

simple-smart-test.pl - Very simple SMART data test

=head1 DESCRIPTION

Direct SMART data collection and database storage test.

=cut

use strict;
use warnings;
use DBI;
use JSON::XS;

print "=== Simple SMART Test ===\n\n";

# Database connection
my $dsn = "DBI:Pg:dbname=autosmart;host=192.168.2.102;port=5432";
my $dbh = DBI->connect($dsn, "autosmart", "autoSMART2025!", {
    RaiseError => 1,
    AutoCommit => 1,
    PrintError => 0
}) or die "Failed to connect to database: $DBI::errstr\n";

print "✓ Database connected\n";

# Test SMART data collection manually
my @devices = glob('/dev/sd[a-z]');

for my $device (@devices) {
    print "\nTesting device: $device\n";
    
    # Get basic device info
    my $smartctl_output = `smartctl -i $device 2>/dev/null`;
    if ($? != 0) {
        print "  ✗ SMART not available\n";
        next;
    }
    
    # Parse basic info
    my ($model) = $smartctl_output =~ /Device Model:\s+(.+)/;
    my ($serial) = $smartctl_output =~ /Serial Number:\s+(.+)/;
    
    if (!$model || !$serial) {
        print "  ✗ Could not parse model/serial\n";
        next;
    }
    
    print "  Model: $model\n";
    print "  Serial: $serial\n";
    
    # Get SMART attributes
    my $smart_output = `smartctl -A $device 2>/dev/null`;
    my %parameters;
    
    # Parse SMART attributes
    for my $line (split /\n/, $smart_output) {
        if ($line =~ /^\s*(\d+)\s+(\w+)\s+0x[\da-f]+\s+(\d+)\s+(\d+)\s+(\d+)\s+\S+\s+\S+\s+\S+\s+(\d+)/) {
            my ($id, $name, $current, $worst, $threshold, $raw) = ($1, $2, $3, $4, $5, $6);
            $parameters{$name} = $raw;
        }
    }
    
    # Get temperature
    my $temp = $parameters{'Temperature_Celsius'} || 0;
    print "  Temperature: ${temp}°C\n";
    print "  Parameters: " . scalar(keys %parameters) . "\n";
    
    # Check if HDD exists in inventory
    my $sth = $dbh->prepare("SELECT id FROM hdd_inventory WHERE serial_number = ? AND model_name = ?");
    $sth->execute($serial, $model);
    my ($hdd_id) = $sth->fetchrow_array();
    
    if (!$hdd_id) {
        # Create new HDD
        print "  Creating new HDD entry...\n";
        $sth = $dbh->prepare(q{
            INSERT INTO hdd_inventory 
            (serial_number, model_name, current_device_path, current_node_id, status)
            VALUES (?, ?, ?, 'ebony', 'active')
            RETURNING id
        });
        $sth->execute($serial, $model, $device);
        ($hdd_id) = $sth->fetchrow_array();
        print "  ✓ HDD created with ID: $hdd_id\n";
    } else {
        print "  ✓ HDD exists with ID: $hdd_id\n";
        # Update location
        $sth = $dbh->prepare("UPDATE hdd_inventory SET current_device_path = ?, last_seen = NOW() WHERE id = ?");
        $sth->execute($device, $hdd_id);
    }
    
    # Store SMART reading
    print "  Storing SMART reading...\n";
    my $parameters_json = encode_json(\%parameters);
    
    $sth = $dbh->prepare(q{
        INSERT INTO smart_readings
        (hdd_id, serial_number, device_path, node_id, timestamp, 
         collection_ok, temperature, parameters_json, reading_type)
        VALUES (?, ?, ?, 'ebony', NOW(), true, ?, ?, 'full')
    });
    
    $sth->execute($hdd_id, $serial, $device, $temp, $parameters_json);
    print "  ✓ SMART reading stored\n";
}

# Show results
print "\n=== Database Summary ===\n";

my $sth = $dbh->prepare("SELECT COUNT(*) FROM hdd_inventory");
$sth->execute();
my ($hdd_count) = $sth->fetchrow_array();
print "HDD Inventory: $hdd_count drives\n";

$sth = $dbh->prepare("SELECT COUNT(*) FROM smart_readings");
$sth->execute();
my ($reading_count) = $sth->fetchrow_array();
print "SMART Readings: $reading_count readings\n";

# Show latest readings
$sth = $dbh->prepare(q{
    SELECT hi.serial_number, hi.model_name, sr.timestamp, sr.temperature
    FROM smart_readings sr
    JOIN hdd_inventory hi ON sr.hdd_id = hi.id
    ORDER BY sr.timestamp DESC
    LIMIT 5
});
$sth->execute();

print "\nLatest readings:\n";
while (my $row = $sth->fetchrow_hashref()) {
    printf "  %s (%s) - %s - %d°C\n",
           substr($row->{serial_number}, 0, 12),
           substr($row->{model_name}, 0, 20),
           $row->{timestamp},
           $row->{temperature} || 0;
}

$dbh->disconnect();
print "\n=== Test Complete ===\n";
