#!/usr/bin/perl

# Created on: 2014-01-10 09:11:44
# Create by:  dev
# $Id$
# $Revision$, $HeadURL$, $Date$
# $Revision$, $Source$, $Date$

use strict;
use warnings;
use version;
use Carp;
use Getopt::Long;
use Pod::Usage;
use Data::Dumper qw/Dumper/;
use English qw/ -no_match_vars /;
use FindBin qw/$Bin/;

our $VERSION = version->new('0.0.3');
my ($name)   = $PROGRAM_NAME =~ m{^.*/(.*?)$}mxs;

my %option = (
    verbose => 0,
    man     => 0,
    help    => 0,
    VERSION => 0,
);

if ( !@ARGV ) {
    pod2usage( -verbose => 1 );
}

main();
exit 0;

sub main {

    Getopt::Long::Configure('bundling');
    GetOptions(
        \%option,
        'first|f!',
        'watch|w=s@',
        'git|g',
        'test|t!',
        'verbose|v+',
        'man',
        'help',
        'version',
    ) or pod2usage(2);

    if ( $option{'version'} ) {
        print "$name Version = $VERSION\n";
        exit 1;
    }
    elsif ( $option{'man'} ) {
        pod2usage( -verbose => 2 );
    }
    elsif ( $option{'help'} ) {
        pod2usage( -verbose => 1 );
    }
    elsif ( !$option{watch} && !$option{git} ) {
        warn "You must specify files to watch!\n";
        pod2usage( -verbose => 1 );
    }
    elsif ( !@ARGV ) {
        warn "No command to run!\n";
        pod2usage( -verbose => 1 );
    }

    # do stuff here
    my %watch;
    my $vcs;
    if ( $option{watch} ) {
        %watch = map { $_ => modified($_) } @{ $option{watch} };
    }
    if ( $option{git} ) {
        require VCS::Which;
        $vcs = VCS::Which->new;
    }

    my $cmd   = join ' ', @ARGV;
    my $count = 0;
    while (1) {
        my $changed = 0;
        my $message = '';
        $count++;
        if ( $vcs && ( !%watch || $count % 5 == 0 ) ) {
            my $status = $vcs->status('.');
            %watch = ( %watch, map { $_ => modified($_) } map { @{ $status->{$_} } } grep {$_ ne 'merge'} keys %{ $status } );
        }

        for my $name (keys %watch) {
            my $mod = modified($name) || 0;
            if ( !$watch{$name} ) {
                if ($mod) {
                    $watch{$name} = $mod;
                }
                else {
                    delete $watch{$name};
                }
            }
            if ( $watch{$name} ne $mod ) {
                $message .= "\n$name has changed, running command\n" if $option{verbose};
                $message .= "\tModified time $mod (was $watch{$name})\n" if $option{verbose} > 1;
                $changed = 1;
            }
        }

        if ( $changed || ( $option{first} && $count == 1 ) ) {
            print "\n";
            warn "--\n$cmd\n--\n" if $option{verbose} > 2;
            system $cmd if !$option{test};
            warn $message if $message;
            print {*STDERR} "\a\n";
        }

        # reset modified times (in case $cmd further modifies those files)
        for my $name (keys %watch) {
            $watch{$name} = modified($name);
        }

        sleep 1;
        print {*STDERR} '.';
    }

    return;
}

sub modified {
    confess "No file passed!\n" if !$_[0];
    return -e $_[0] && (stat $_[0])[9];
}

__DATA__

=head1 NAME

watch-do - Run a command when watched files change

=head1 VERSION

This documentation refers to watch-do version 0.0.3

=head1 SYNOPSIS

   watch-do [option]
   watch-do -w file1 [-w file2 ...] [--] cmd

 OPTIONS:
  cmd               Command to run when file changes
  -w --watch[=]file File to be watched for changes
  -g --git          Use git to find what to watch (ie monitor files that git see have changed)

  -v --verbose      Show more detailed option
     --version      Prints the version information
     --help         Prints this help information
     --man          Prints the full documentation for watch-do

=head1 DESCRIPTION

=head1 SUBROUTINES/METHODS

=head1 DIAGNOSTICS

=head1 CONFIGURATION AND ENVIRONMENT

=head1 DEPENDENCIES

=head1 INCOMPATIBILITIES

=head1 BUGS AND LIMITATIONS

There are no known bugs in this module.

Please report problems to Ivan Wills (ivan.wills@gmail.com).

Patches are welcome.

=head1 AUTHOR

Ivan Wills - (ivan.wills@gmail.com)

=head1 LICENSE AND COPYRIGHT

Copyright (c) 2014 Ivan Wills (14 Mullion Close, Hornsby Heights, NSW Australia 2077).
All rights reserved.

This module is free software; you can redistribute it and/or modify it under
the same terms as Perl itself. See L<perlartistic>.  This program is
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

=cut
