#!/usr/local/bin/perl -w
###########################################
# dropbox-gitgetter -- Get forgotten git
#  updates via dropbox.com
# Mike Schilli, 2011 (m@perlmeister.com)
###########################################
use strict;
use MyDropbox;
use App::Daemon qw( daemonize );
use Log::Log4perl qw(:easy);
use HTTP::Status qw(:constants);
use File::Temp qw(tempfile);
use Cwd qw(realpath);
use Sysadm::Install qw(:all);
use File::Basename;

Log::Log4perl->easy_init($DEBUG);

daemonize();

my $mod_hash      = undef;
my $poll_interval = 60;

my $box = MyDropbox->new();
$box->context( "dropbox" );

my($home) = glob "~";
my $gitdir = realpath "$home/git";

while( 1 ) {
  my @hash_args = ();
  @hash_args = ( hash => $mod_hash ) if
    defined $mod_hash;

  my $href = $box->list( { @hash_args },
    "/gitgetter" );

  if( $href->{http_response_code} eq 
      HTTP_NOT_MODIFIED ) {
      DEBUG "Not modified";
  } else {
      $mod_hash = $href->{hash};
      request_handler( $box );
  }

  DEBUG "Sleeping ${poll_interval}s";
  sleep $poll_interval;
}

###########################################
sub request_handler {
###########################################
  my($box) = @_;

  my $content = 
   $box->getfile("gitgetter/requests.txt");

  my $pushed = 0;

  for my $line ( split /\n/, $content ) {
    $line =~ s/#.*//;
    next if $line =~ /^\s*$/;
    DEBUG "Found request: '$line'";

    my $file = realpath( "$gitdir/$line" );
    if( $file !~ /^$gitdir/ ) {
        ERROR "Path $file denied.";
        next;
    }

    DEBUG "Delivering $file";

    if( !-f $file ) {
      ERROR "$file doesn't exist";
      next;
    }

    my $href = $box->putfile( $file, 
        "gitgetter" );
    $pushed++;
  }

  if( $pushed ) {
    my($fh, $tmpfile) = tempfile( 
        UNLINK => 1 );
    blurt "# pending requests\n", $tmpfile;
    my $href = $box->putfile( $tmpfile, 
        "gitgetter", "requests.txt" );
  }
}
