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

use strict;

require PleskMaxVersion;
require AgentConfig;

my ($major, $minor, $minorMinor, $smb);

sub init {
  my ($productRootD) = @_;

  my $versionFile = (-d $productRootD) ? "$productRootD/version" : "/usr/local/psa/version";

  $smb = _checkSmb($productRootD);

  open(VERSION, "< $versionFile") || die "Unable to find Plesk versionfile: $versionFile";
  binmode (VERSION);
  my $out = <VERSION>;
  chomp $out;
  close(VERSION);

  if ($out =~ /^(\d+)\.(\d+)(.*)$/) {
    $major = $1;
    $minor = $2;

    if ($3 =~ /^\.(\d+)/) {
      $minorMinor = $1;
    } else {
      $minorMinor = 0;
    }
  }
}

sub _checkSmb {
  my $productRootD = shift;
  
  if (-d "$productRootD/admin/smb") {
    my $command = AgentConfig::getProductModeCommand();
    if ( $command) {
      my $cmd = $command . " --get-mode";
      Logging::debug( "Exec: $cmd" );
      my $ret = `$cmd`;
      my $retCode = $? >> 8;
      if( $retCode!=0 ){
        Logging::warning( "Cannot detect product mode", 'UtilityError' );
        return 0;
      }
      if ($ret eq 'SMB') {
        return 1;
      }else{
        return 0;
      }
    } else {
      return 1;
    }
  } else {
    return 0;
  }
}

sub get {
  if ($major) {
    return "$major.$minor.$minorMinor";
  }
}

sub isSmb {
  return $smb;
}

# 2.5 <= ver <= last known plesk version
sub isSupported {
  return 1 if $smb;

  return 0 if $major < 8;

  return 0 if $major > $PleskMaxVersion::major;
  return 0 if $major == $PleskMaxVersion::major and $minor > $PleskMaxVersion::minor;
  return 0 if $major == $PleskMaxVersion::major and $minor == $PleskMaxVersion::minor
    and $minorMinor > $PleskMaxVersion::minorMinor;

  return 1;
}

sub atLeast {
  my ($lim_major, $lim_minor, $lim_minorMinor) = @_;

  return 1 if $major > $lim_major;
  return 1 if $major == $lim_major and $minor > $lim_minor;
  return 1 if $major == $lim_major and $minor == $lim_minor and $minorMinor >= $lim_minorMinor;

  return 0;
}


1;
