package SVN::Hooks::HupServer;

use strict;
use warnings;
use SVN::Hooks;

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

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

sub HUP_SERVER {
    my $conf = $SVN::Hooks::Confs->{$HOOK};
    die "Invalid: odd number of arguments" if @_ % 2;
    while (my ($path_regexp, $config) = splice(@_,0,2) ) {
      push @{$conf->{options}}, { regexp => $path_regexp,
				  %$config };
    }

    $conf->{'post-commit'} = \&post_commit;
    return 1;
};

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

sub post_commit {
  my ($self, $svnlook) = @_;
  my @dir_changed = $svnlook->dirs_changed;
  for my $hup (@{$self->{options}}) {
    if (grep $_ =~ $hup->{regexp}, @dir_changed) {
      # /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(' ',
			      $hup->{ssh_path},
			      '-i', $hup->{identity_file},
			      '-l', $hup->{apache_user},
			      $hup->{remote_host},
			      $hup->{apache_path},
			      '-d', $hup->{server_root},
			      '-f', $hup->{config_path},
			      '-k', 'restart'
			     );
      system("${command_line} 2>&1 &");
      die if $? >> 8 ;
    }
  }
  return;
}



1;
