#!/usr/bin/perl -w

use strict;
use Sys::Guestfs;

if (@ARGV < 1) {
    die "usage: mostrecent.pl disk.img"
}

my $disk = $ARGV[0];

my $g = new Sys::Guestfs ();

# Attach the disk image read-only to libguestfs.
$g->add_drive_opts ($disk, readonly => 1);

# Run the libguestfs back-end.
$g->launch ();

# Ask libguestfs to inspect for operating systems.
my @roots = $g->inspect_os ();
if (@roots == 0) {
    die "inspect_vm: no operating systems found";
}

# Find /var/log/messages on each root.
my $youngest_root;
my $youngest_root_mtime;
my $root;

for $root (@roots) {
    # Mount up the disks, like guestfish -i.
    my %mps = $g->inspect_get_mountpoints ($root);
    my @mps = sort { length $a <=> length $b } (keys %mps);
    for my $mp (@mps) {
        eval { $g->mount_ro ($mps{$mp}, $mp) };
        if ($@) {
            print "$@ (ignored)\n"
        }
    }

    # Get the age of /var/log/messages.
    my %stat = $g->stat ("/var/log/messages");
    my $mtime = $stat{mtime};
    my $set = 1;
    if (defined $youngest_root) {
        $set = $mtime > $youngest_root_mtime;
    }
    if ($set) {
        $youngest_root = $root;
        $youngest_root_mtime = $mtime;
    }

    # Unmount everything.
    $g->umount_all ()
}

if (defined $youngest_root) {
    print "Youngest root filesystem is: $youngest_root\n";
}
else {
    print "No suitable root filesystem found (is it a Linux guest?)\n";
}
