#!/usr/bin/perl

use strict;
use warnings;
use Time::Piece;
use File::Find;

my $date = localtime->strftime('%Y-%m-%d');

# First, every operation starts with going to the ratf dir
chdir "/home/dave/wiki/ratf";

my $cmd = ($ARGV[0] or '');

   if ($cmd eq 'edit') { rat_edit(); }
elsif ($cmd eq 'feed') { rat_feed(); }
elsif ($cmd eq 'new')  { rat_new(); }
elsif ($cmd eq 'dirs') { rat_dirs(); }
elsif ($cmd eq 'grep') { rat_grep(); }
elsif ($cmd eq 'lsd')  { rat_lsd(); }
elsif ($cmd eq 'pub')  { rat_pub(); }
elsif ($cmd eq 'card') { rat_card(); }
elsif ($cmd eq 'book') { rat_book(); }
elsif ($cmd eq 'exif') { rat_exif(); }
else {
    print q{Usage:
    rat edit <page_name> (lists partial matches)
    rat feed [<page_name> (lists partial matches)] opens atom.xml
    rat new  <page_name>
    rat dirs             (list all dirs under ratf/src/)
    rat grep             (searches all .adoc files)
    rat lsd              (list all drafts)
    rat pub
    rat book             (open b/ (books) index)
    rat exif             (strip exif data from images)
};
}

# PUB
###########################################################################
sub rat_pub {
    system qw( ./make.rb );
    system qw( rsync -av --exclude '*~' --exclude '.*' src/ ratf:www/ );
}

# EDIT
###########################################################################
sub rat_edit {
    my $page = $ARGV[1] or die "Edit requires page name!\n";

    my $fname = '';

    if ($page eq 'index') {
        # exactly 'index' should always open THE index
        $fname = './src/index.adoc';
    }
    else {
        $fname = pagepicker($page);
    }
    print "Cool, opening $fname...\n";

    system ('vim', $fname);
}

# CARD
###########################################################################
sub rat_card {
    my $fname = 'src/cards/index.adoc';
    print "Cool, opening $fname...\n";

    system ('vim', $fname);
}

# BOOKS
###########################################################################
sub rat_book {
    my $fname = 'src/b/index.adoc';
    print "Cool, opening $fname...\n";

    system ('vim', $fname);
}

# FEED
###########################################################################
sub rat_feed {
    my $page = $ARGV[1];
    my $atom = 'src/atom.xml';

    if ($page) {
        my $fname = pagepicker($page);
        print "Cool, adding $fname...\n";
        add_to_feed($fname, $atom);
    }

    system ('vim', $atom);
}

# EXIF
###########################################################################
sub rat_exif {
    my $output = `git ls-files -o -m --exclude-standard`;
    my @files = split(/\n/, $output);
    my $fcount = @files;
    print "Site has $fcount changed files...\n";
    foreach (@files) {
        if($_ =~ /\.(jpg|png)$/){
            print "Found: $_\n";
            print `exiftool -all= -overwrite_original_in_place "$_"`
        }
    }
    print "Done.\n";
}

# NEW
###########################################################################
sub rat_new {
    my $page = $ARGV[1] or die "New requires page name!\n";

    my $newfname = "src/$page.adoc";

    die "$newfname already exists!\n(Edit with 'rat edit $page' intead.)\n" if (-e $newfname);

    open(my $fh, '>', $newfname) or die "Could not open '$newfname': $!\n";
print $fh qq{:title: $page
:subtitle: Stuff
:created: $date
:updated: $date
:updated_reason:
:draft: true

};
    close $fh;
    
    print "Editing new $newfname...\n";
    system ('vim', $newfname);
}

# DIRS
###########################################################################
sub rat_dirs {
    foreach(glob('src/*')){
        my $withoutsrc = s/src\///r; # 'r' modifier keeps original intact
        print "\t$withoutsrc\n" if -d;
    }
}

# GREP
###########################################################################
sub rat_grep {
    my $search = $ARGV[1] or die "Search for what?\n";
    #find( sub { push @matches, $File::Find::name if ( $File::Find::name =~ /$page.*\.adoc$/ ) }, '.' );
    system ('ag', '-G', '.adoc$', $search );
}

# LSD (List Drafts)
###########################################################################
sub rat_lsd {
    print "TODO!\n";
    #find( sub { push @matches, $File::Find::name if ( $File::Find::name =~ /$page.*\.adoc$/ ) }, '.' );
}


###########################################################################
###########################################################################

sub pagepicker {
    my $page = shift;

    my @matches = ();
    find( sub { push @matches, $File::Find::name if ( $File::Find::name =~ /$page.*\.(adoc|html)$/ ) }, '.' );

    my $match_count = scalar @matches;

    if ($match_count > 1) {
        my $num = 1;
        print "Which match?\n";
        print "-------------------\n";
        print "0. CANCEL\n";
        for (@matches) {
            print "$num. $_\n";
            $num++;
        }
        print "-------------------\n";
        print "> ";
        my $selection = <STDIN>;
        chomp $selection;
        if ($selection == 0) {
            die "Okay, bye!\n";
        }
        $selection--;
        die "Invalid selection!\n" unless (defined $matches[$selection]);

        return $matches[$selection];
    }
    elsif ($match_count == 1)
    {
        return $matches[0];
    }

    die "Found no pages matching '$page'. :-(\n";
}

sub add_to_feed {
    my $fname = shift;
    my $atom = shift;
    my $title = "";
    my $subtitle = "";

    my $page_path = substr $fname, 6, -5; # chop './src/' off of front, .adoc off end

    open(my $fh, '<', $fname) or die "Could not open '$fname': $!\n";
    while( my $line = <$fh>)  {   
        $title = $1 if($line =~ /:title: (.*)$/);
        $subtitle = $1 if($line =~ /:subtitle: (.*)$/);
        last if $line =~ /^\s*$/; # empty line is end of page metadata
    }
    close $fh;

    open(my $fh2, '>>', $atom) or die "Could not open '$atom': $!\n";
    print $fh2 qq{
    TODO: delete </feed> above!!!!
    <entry>
        <title>$title</title>
        <link href="http://ratfactor.com/$page_path" />
        <id>http://ratfactor.com/$page_path</id>
		<updated>${date}T00:00:00Z</updated>
        <author><name>Dave Gauer</name></author>
        <summary>
            $subtitle ...
        </summary>
	</entry>

</feed>};
    close $fh2;
}
