# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
package ConfixxConfigPath;

use strict;
use warnings;
use AgentConfig;

sub getConfixxMainConfigPath() {
  return 
    _guessConfixxMainConfigPathFromEnv() ||
    _guessConfixxMainConfigPathFromStandardPaths() ||
    _guessConfixxMainConfigPathFromCrontab();
}

sub _guessConfixxMainConfigPathFromEnv {
  if (exists($ENV{'CONFIXX_ROOT'} ) && -d $ENV{'CONFIXX_ROOT'}) {
    my $path = $ENV{'CONFIXX_ROOT'} . '/confixx_main.conf';
    return $path if -r $path;
  }

  return undef;
}

sub _guessConfixxMainConfigPathFromStandardPaths {
  foreach my $prefix ('./','/root/confixx/','/usr/local/confixx/','/confixx/') {
    my $path = $prefix . 'confixx_main.conf';
    return $path if -r $path;
  }

  return undef;
}

sub _guessConfixxMainConfigPathFromCrontab {
  return 
    _guessConfixxMainConfigPathFromCrontabCommand(AgentConfig::grepBin() . ' -hr confixx /etc/crontab /etc/cron.d') ||
    _guessConfixxMainConfigPathFromCrontabCommand(AgentConfig::crontabBin() . ' -l');
}

sub _guessConfixxMainConfigPathFromCrontabCommand {

  my ($crontabLinesCommand) = @_;

  foreach my $line (`$crontabLinesCommand`) {
    chomp $line;
    next if ( $line =~ /^\s*#/ ); # skip comment line

    my @lineParts = split(' ', $line);
    my $command = $lineParts[scalar(@lineParts) - 1]; # we assume that the last part of a line is a command
    if ($command =~ /^(.*)\/[^\/]*$/) {
      my $commandBaseDir = $1;
      my $path = $commandBaseDir. '/confixx_main.conf';

      return $path if -r $path;
    }
  }

  return undef;
}

1;
