#!/usr/bin/perl

use warnings;
use strict;

my $drive = $ARGV[0] || die "usage: $0 /dev/sda\n";
my $delay = 15;
my $rewrite_sectors = 16;

my $test_started = 0;

sub smart_test {
	my $sector = shift;
	my $cmd = "smartctl -t select,$sector-max $drive";
	warn "$cmd\n";
	system $cmd;
	$test_started = 1;
}

sub smart {
	open(my $fh, '-|', "smartctl -l selective $drive");
	while(<$fh>) {
		chomp;
		print "# $_\n";
		if ( m/Completed_read_failure.*\((\d+)-\d+\)/ ) {
			my $sector = $1;
			print "rewrite sector: $sector\n";
			foreach my $s ( $sector .. $sector + $rewrite_sectors ) {
				system "hdparm --write-sector $s --yes-i-know-what-i-am-doing $drive";
			}
			smart_test $sector;
			return 1;
		} elsif ( m/Self_test_in_progress/ ) {
			return 1;
		} elsif ( m/Not_testing/ ) {
			return 1 if $test_started;
			smart_test 0; # first-time invocation
		}
	}
	return 0;
}

while ( smart ) {
	warn "# sleep $delay s\n";
	sleep $delay;
}
