package SVN::Hooks::PostRsync;

use strict;
use warnings;
use SVN::Hooks;
use Data::Dumper;

use Exporter qw/import/;
my $HOOK = 'ZZZPOST_RSYNC'; # force to be near the end of the list
our @EXPORT = qw/POST_RSYNC/;

our $VERSION = $SVN::Hooks::VERSION;

sub POST_RSYNC {
    my $conf = $SVN::Hooks::Confs->{$HOOK};
    die "Invalid: odd number of arguments" if @_ % 2;
    $conf->{options} = {@_};
    $conf->{'post-commit'} = \&post_commit;
    return 1;
};

$SVN::Hooks::Inits{$HOOK} = sub {
    return { options => [] };
};

sub _projects_to_handle {
  my $self = shift;
  my %project_to_handle;
  for my $dir_changed (@_) {
    if ((my $project) = $dir_changed =~ $self->{options}{regex} ) {
      $project_to_handle{$project}++;
    }
  }
  return keys %project_to_handle;
}

sub _handle_a_project {
  my $self = shift;
  my $project_name = shift;

  # /usr/sbin/ssh
  # -i /usr/local/svn/private/sb6-www-identity \
  # -l www-data \
  # sb6.barkani.com \
  # /web-svn/${project_name}/bin/post-rsync
  # /web-svn/${project_name}
  # /tmp/${project_name}

  my $command_line = join(' ',
			  $self->{options}{ssh_path},
			  '-i', $self->{options}{identity_file},
			  '-l', $self->{options}{apache_user},
			  $self->{options}{remote_host},
			  sprintf($self->{options}{rsync_script_template},$project_name),
			  '--server_root', sprintf($self->{options}{server_root_template},$project_name),
			  '--var_root', sprintf($self->{options}{var_root_template},$project_name),
			  '--port', 1088, # not really -- I'm just passing this and it does not get used
			 );
      system("${command_line} 2>&1 &");
      die if $? >> 8 ;
}

sub post_commit {
  my $self = bless shift,__PACKAGE__;
  my $svnlook = shift;

  my @dir_changed = $svnlook->dirs_changed();
  if (my @project_to_handle = $self->_projects_to_handle ($svnlook->dirs_changed)) {
    $self->_handle_a_project($_)
      for @project_to_handle;
  }
  return;
}

1;
