#!/usr/bin/perl
# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

package ApacheAgent;


use Apache::ConfigFile;
use HelpFuncs;
use Logging;
use AgentConfig;
use DomainInfo;


sub new {
  my $self = { };
  bless($self);

  return $self;
}


sub get_installed {
  return 1 if AgentConfig::findApacheHttpdBin() and ( AgentConfig::apachectlBin() or AgentConfig::apache2ctlBin() );
  return 0;
}

sub get_id_string{
  my $self = shift;
  return 'Apache';
}

sub get_version{
  my $self = shift;
  my $apache = AgentConfig::findApacheHttpdBin();
  my $version = `$apache`;
  chomp $version;
  if ($version =~ /Server\s+version:\s+([^\/]*)\/(\d+\.\d+\.\d+)/) { return $2; }
  return undef;
}

sub get_display_name{
  my $self = shift;
  return 'Apache v.' . $self->get_version();
}

sub getApacheDomainInfo {
  my $self = shift;

  my %info =  $self->mainApacheConfig();
  my $root = $info{'root'} || HelpFuncs::dieWithError( "Cannot determine Apache root directory!" );
  my $cfg = $info{'cfg'} || HelpFuncs::dieWithError( "Cannot determine Apache main config file!" );
  $cfg = "$root/$cfg" if $cfg !~ m!^/!;

  my $dInfo = DomainInfo->new();
  $Apache::ConfigFile::server_root = $root;
  $self->{config} = Apache::ConfigFile->new( $cfg );
  my @vhkeys = $self->{config}->cmd_context('VirtualHost');

  foreach my $vhkey (@vhkeys) {
    Logging::debug( "Parse VirtualHost: $vhkey" );
    next if ($vhkey=~/\_+|\*+/);
    foreach my $vh ($self->{config}->cmd_context(VirtualHost => $vhkey)) {
      my $sname = $vh->cmd_config('ServerName');
      Logging::debug( "Parse ServerName: $sname" );
      my $ip = $vhkey;
      $ip  =~ s/:[0-9]+//g;
      my $dname = $sname;
      $dname =~ s/:[0-9]+//g;
      Logging::debug( "Found domain $dname at $ip" );
      if( $dInfo->add_domain( $dname, $ip ) ){
        #TO DO
      }
    }
  }
  return $dInfo;
}


sub getApacheVHostConfig {
  my( $self, $domain_name ) = @_;

  return undef if not exists $self->{config};

  my @vhkeys = $self->{config}->cmd_context('VirtualHost');

  foreach my $vhkey (@vhkeys) {
    next if ($vhkey=~/\_+|\*+/);
    foreach my $vh ($self->{config}->cmd_context(VirtualHost => $vhkey)) {
      my $sname = $vh->cmd_config('ServerName');
      $sname =~ s/:[0-9]+//g;
      return $vh if $sname eq $domain_name;
    }
  }
  return undef;
}


sub mainApacheConfig {
  my $self = shift;
  my $apache = AgentConfig::findApacheHttpdBin();
  Logging::debug("Parse apache httpd info: $apache ");

  my $config;
  my $httpdroot;

  open (CTL, "$apache -V|");
  while (<CTL>) {
    chomp;
    if ($_=~/\w+\s+SERVER_CONFIG_FILE=(.+)/) {
      $config = $1;
      $config=~s/"//g;
    }
    if ($_=~/\w+\s+HTTPD_ROOT=(.+)/) {
      $httpdroot = $1;
      $httpdroot=~s/"//g;
    }
  }
  close CTL;

  Logging::debug("Apache httpd root '$httpdroot', config path $config'");

  return ( 'root' => $httpdroot, 'cfg' => $config );
}





1;