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

use strict;

require PleskMaxVersion;
require AgentConfig;

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

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

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

  $productName = _getProductName($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 _getProductName {
  my $productRootD = shift;

  if (-d "$productRootD/admin/smb") {
    my $productMode = $ENV{'PRODUCT_MODE'};
    if ($productMode) {
      return $productMode;
    }
    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 "PLESK";
      }
      if ($ret eq 'SMB' or $ret eq 'SHM') {
         return $ret;
      } else{
        return "PLESK";
      }
    } else {
      return "SMB";
    }
  } else {
    return "PLESK";
  }
}

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

sub isShm {
    return $productName eq "SHM";
}

# 8.6 <= ver <= last known plesk version
sub isSupported {

  return 0 if $productName eq "SMB";

  return 0 if $major < 8 || ($major == 8 && $minor < 6);

  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;
