#!/usr/bin/perl -w
use strict;
use warnings;
use Date::Parse;

my $day = 24*3600;
my $warn_mounts_to_go = 3;
my $warn_days_to_go = 3;  # days

my $verbose = @ARGV && $ARGV[0] eq "-v" && shift() ? 1 : 0;

my @devices = @ARGV;
if (!@devices) {
	@devices = qw(/dev/sda1);
}

#Mount count:              1
#Maximum mount count:      27
#Next check after:         Wed Sep  5 14:03:03 2012

my @warn_devices;

for my $d (@devices) {
	my $info = `tune2fs -l \Q$d\E`;
	my @lines = split /\n/, $info;
	shift @lines if $lines[0] =~ /^tune2fs/;
	exit(1) if !@lines;
	@lines = grep /:/, @lines;
	my %info = map { split /: */, $_, 2 } @lines;
	my $mount_count = $info{'Mount count'};
	my $maximum_mount_count = $info{'Maximum mount count'};
	my $next_check_after = $info{'Next check after'};

	my $mounts_to_go = $maximum_mount_count - $mount_count;
	my $days_to_go = sprintf("%.0f", (str2time($next_check_after) - time()) / $day);
	
	if ($verbose) {
		print "mounts_to_go: $mounts_to_go, days_to_go: $days_to_go\n";
	}

	if ($mounts_to_go <= $warn_mounts_to_go || $days_to_go <= $warn_days_to_go) {
		push @warn_devices, $d;
	}
}

if (@warn_devices) {
	print "The following devices need an fsck soon: @warn_devices\n";
	print "As root, you can force an fsck on next boot with:\n";
	print <<'End';
  touch /forcefsck
End
	print "You can reboot, fsck, then halt, with:\n";
	print <<'End';
  touch /forcefsck
  echo '@reboot root rm -f /etc/cron.d/haltonce && /sbin/halt' > /etc/cron.d/haltonce
  reboot
End
	print "Or, use:\n";
	print <<'End';
  fsck-halt
End
}

