#!/usr/bin/env perl
#
# watchdiff - like watch(1), but output in diff format
# dependencies: waitpid
#
# ---
# see: dwatch (caches in order to allow diffs to span invocations)
# source: https://github.com/aspiers/shell-env

use strict;
use warnings;

use File::Copy;
use File::Spec;
use File::Temp qw(tempfile);
use Getopt::Long;
use IPC::Open2;
use Time::HiRes qw(sleep);

$| = 1;

my $DEFAULT_INTERVAL = 2.0;
my $tmpdir           = File::Spec->tmpdir;
my ( $old_fh, $old_fn ) = tempfile( "watchdiff-$$-old-XXXXXX", DIR => $tmpdir );
my ( $new_fh, $new_fn ) = tempfile( "watchdiff-$$-new-XXXXXX", DIR => $tmpdir );
$SIG{INT} = \&clean_up;

my $columns =
  $ENV{COLUMNS} || ( `stty -a -F /dev/stderr` =~ /columns (\d+)/ )[0];

sub usage {
    warn @_, "\n" if @_;

    ( my $cmd_name = $0 ) =~ s,.*/,,;

    die <<EOUSAGE;
Usage: $cmd_name [OPTIONS] CMD [ARGS]
Options:
  -h, --help           Show this help
  -n, --interval=N     Run command every N seconds (default $DEFAULT_INTERVAL)
  -d, --clear          Clear screen before displaying each diff
  -c, --cumulative     Show cumulative differences
EOUSAGE
}

sub parse_opts {
    Getopt::Long::Configure('require_order');

    my %opts = ( interval => $DEFAULT_INTERVAL );
    GetOptions( \%opts, 'help|h', 'interval|n=f', 'clear|d', ) or usage();
    usage() if @ARGV == 0                                      or $opts{help};

    return %opts;
}

sub run_command {
    my @args = @_;

    my ( $stdin, $stdout );
    my $pid = open2( $stdout, $stdin, @args );
    seek $new_fh, 0, 0;
    truncate $new_fh, 0;
    print $new_fh $_ while <$stdout>;
    waitpid $pid, 0;
}

sub delimiter {
    print "=" x ( $columns - 1 ), "\n";
}

{
    my $diff_count = 0;

    sub do_comparison {
        my ($opts) = @_;

        my $cmd    = "diff -u $old_fn $new_fn";
        my $diff   = `$cmd`;
        my $status = $? >> 8;
        die "$cmd failed; aborting.\n" if $status == 2;
        my $changed = $status == 1;

        return unless $changed;

        if ( $opts->{clear} ) {
            system 'clear';
        }
        else {
            delimiter() if $diff_count++;
        }

        print $diff;
    }
}

sub main {
    my %opts  = parse_opts();
    my $count = 0;

    while (1) {
        run_command(@ARGV);

        if ( $count > 0 ) {
            do_comparison( \%opts );
        }
        else {
            system 'cat', $new_fn;
            delimiter();
        }

        copy( $new_fn, $old_fn ) if !$opts{cumulative} or $count == 0;

        $count++;

        sleep $opts{interval};
    }
}

sub clean_up {
    close $old_fh;
    close $new_fh;
    unlink $old_fn, $new_fn;
    exit;
}

main();
