package SI::system;

use strict;
use warnings;
use File::Temp qw(tempdir);
use if $ENV{DEBUG} ~~ qw(system) => "Smart::Comments";
use SI::tools;

$ENV{LC_ALL} = "C";

sub id() {

    $_ = `ip link`;
    s/\n\s+/ /g;
    s/^\d+:\s*//mg;

    (sort grep /^(eth|wlan)/, split /\n/, $_)[0]
	=~ /link\/ether\s+(?<mac>\S+)/
      and return $+{mac};

    die "ERR: Can't get system identification (MAC address)\n";
}

sub hostname(\%) {
    my $devs = shift;
    my $mnt = tempdir(CLEANUP => 1);
    my $h;

    foreach my $fs (
        grep {
            exists $devs->{volume}{$_}{type}
              and $devs->{volume}{$_}{type} =~ /^ext/i
        } @{ $devs->{volumes} }
      )
    {
        run("mount -r $fs $mnt");
        if (-f "$mnt/etc/hostname") {
            chomp($h = cat("$mnt/etc/hostname"));
        }
        run("umount $mnt");
        return $h if defined $h;
    }

    return $h;
}

sub fsck(\%) {
    my $devs = shift;

    foreach
      my $v (grep { exists $devs->{volume}{type} } keys %{ $devs->{volume} })
    {
        my $volume = $devs->{volume}{$v};
        next if $volume->{type} !~ /^ext/i;

        system("fsck -C0 $v");
        die "ERR: fsck failed\n" if $? > 2;
    }
}

1;

# vim:sts=4 sw=4 aw ai si:
