package SVN::Hooks::HupDevBranchServer;

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

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

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

sub HUP_DEV_BRANCH {
    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_hup {
  my $self = shift;
  my %project_to_hup;
  for my $dir_changed (@_) {
    if ((my $project) = $dir_changed =~ $self->{options}{regex} ) {
      $project_to_hup{$project}++;
    }
  }
  return keys %project_to_hup;
}

sub _hup_a_project {
  my $self = shift;
  my $project_name = shift;
  my $server_root = sprintf($self->{options}{server_root_template},$project_name);
  my $config_file = sprintf($self->{options}{config_template},$project_name);
  
  # /usr/sbin/ssh
  # -i /usr/local/svn/private/sb6-www-identity \
  # -l www-data \
  # sb6.barkani.com \
  # /usr/sbin/apache2 \
  # -d /web/dev-omni/apache \
  # -f conf/httpd.conf \
  # -k restart
  my $command_line = join(' ',
			  $self->{options}{ssh_path},
			  '-i', $self->{options}{identity_file},
			  '-l', $self->{options}{apache_user},
			  $self->{options}{remote_host},
			  $self->{options}{apache_path},
			  '-d', $server_root,
			  '-f', $config_file,
			  '-k', 'restart'
			 );
      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_hup = $self->_projects_to_hup ($svnlook->dirs_changed)) {
    $self->_hup_a_project($_)
      for @project_to_hup;
  }
  return;
}

1;
