#!/usr/bin/perl

use strict;
use warnings;

my $less = 0;
my $ignore_case = 0;

if (@ARGV == 0 || $ARGV[0] eq "-h" || $ARGV[0] eq "--help") {
    print "usage: [options] pattern file...\n";
    print "       -h    help\n";
    print "       -i    ignore case\n";
    print "       -l    prints as less -p DATE FILE LINE#: ... for paste\n";
    print "             use e.g., dgrep -l PATTERN | cut -d ' ' -f1-4 | sh\n";
    exit;
} elsif ($ARGV[0] eq "-i" || $ARGV[0] eq "--ignore-case") {
    $ignore_case = 1;
    shift;
} elsif ($ARGV[0] eq "-l" || $ARGV[0] eq "--less") {
    $less = 1;
    shift;
}

my $pattern = shift;

my @files = (@ARGV);

if ($files[0]) {
    # We got files on the command line -- use them
} elsif (-f "to.do" && ! -l "to.do") {
    # We're in a directory that contains a to.do file
    @files = split /\n/, `ls */*.done to.do`;
} else {
    # We're in the wrong directory, so look in the right one (...Dog)
    my $path = (-d "~/Private/Journals/Dog")
	? "~/Private/Journals/Dog"
	: "~/vv/users/steve/Private/Journals/Dog";
    $path = `realpath --relative-to . $path`;
    $path =~ s/\n//;
    @files = split /\n/, `ls $path/*/*.done $path/to.do`;
}

while ($files[0]) {
    my $file=shift @files;
    open IN, $file;
    my $date = "";
    my $lnum = 0;
    while (<IN>) {
	my $line = $_;
	$lnum++;
	if (/^(\d\d\d\d)/) {
	    $date=$1;
	}
	if (/$pattern/ || ($ignore_case && /$pattern/i)) {
	    if ($less) {
		print "less -p ^$date $file $lnum: $line";
	    } else {
		print "$file:$lnum: $date: $line";
	    }
	}
    }
    close IN;
}
