#! /usr/bin/perl

# $recoverdir = "/home/kjm/ideon/test/var/tmp/vi.recover";
# $debug = 1;
$recoverdir = "/var/tmp/vi.recover";
$debug = 0;

opendir(RECOVERDIR, $recoverdir) || die "cannnot open $recoverdir\n";
@backupfiles = map "$recoverdir/$_", grep /^vi\./, readdir(RECOVERDIR);
closedir(RECOVERDIR);

foreach $i (@backupfiles) {
    print STDERR "DEBUG: backupfile = $i\n" if $debug;

    next if (! -f $i || ! -r $i);
    unlink $i if (-x $i || ! -s $i);
}

opendir(RECOVERDIR, $recoverdir) || die "cannnot open $recoverdir\n";
@recoverfiles = map "$recoverdir/$_", grep /^recover\./, readdir(RECOVERDIR);
closedir(RECOVERDIR);

foreach $i (@recoverfiles) {
    print STDERR "DEBUG: recoverfile = $i\n" if $debug;

    next if (! -f $i || ! -r $i);

    open(RFILE, $i) || next;
    $recfile = "";
    while (<RFILE>) {
	if (/^X-vi-recover-path:\s+(\S+)/) {
	    $recfile = $1;
	    print STDERR "DEBUG: recfile = $recfile\n" if $debug;
	    last;
	}
    }
    close(RFILE);
    if ($recfile ne "" && -s $recfile) {
	print STDERR "DEBUG: sendmail $i ($recfile)\n" if $debug;
	if (open(SENDMAIL, "sendmail -t < $i |")) {
	    while (<SENDMAIL>) {
		print;
	    }
	    close(SENDMAIL);
	} else {
	    print SEDERR "vi-recover: cannot mail $i\n";
	}
    } else {
	print STDERR "DEBUG: unlink $i\n" if $debug;
	unlink $i;
    }
}

