# Copyright 1999-2015. Parallels IP Holdings GmbH. All Rights Reserved.
package Suspend;

use strict;

sub new {
  my $self = {};
  bless( $self, shift );
  $self->_init(@_);
  return $self;
}

sub _init {
  my ( $self ) = @_;
  $self->{suspend}            = undef;
  $self->{suspendedDomain}    = undef; 
}

sub setSuspend{
  my ( $self, $suspend, $suspendSid ) = @_;
  $self->{suspend} = undef;
  if( $suspend ){
     if( $suspendSid ){
        $self->{suspend} = 1;
        $self->{suspendSid} = $suspendSid;
     }
     else{
        Logging::warning( "Suspend session id is unkwnown. Suspend will be unavailable." );
     }
  }
}
sub suspendDomain{
  my ($self, $domain ) = @_;
  return if not $self->{suspend};
  $self->unSuspendDomain();
  Logging::debug( "Suspend domain '$domain'" );
  my $cmd = AgentConfig::getSuspendCommand();
  if ( $cmd ) {
    $cmd .= " suspend $domain $self->{suspendSid}";
    Logging::debug( "Exec: $cmd" );
    my $ret = `$cmd`;
    my $retCode = $? >> 8;
    if( $retCode!=0 ){
      Logging::warning( "Cannot suspend domain  '$domain' (ErrorCode: $retCode, STDOUT:$ret) [Error:$!]. This is not fatal error!", 'UtilityError' );
      Logging::warning( "The domain '$domain' was not suspended during backup!" ,'SuspendFailed');
      return;
    }
    $self->{suspendedDomain} = $domain;
  }
}

sub unSuspendDomain{
  my ($self ) = @_;
  return if not $self->{suspend};
  return if not $self->{suspendedDomain};
  my $domain = $self->{suspendedDomain};
  Logging::debug( "Resume domain '$domain'" );
  my $cmd = AgentConfig::getSuspendCommand();
  if ( $cmd ) {
    $cmd .= " unsuspend $domain $self->{suspendSid}";
    Logging::debug( "Exec: $cmd" );
    my $ret = `$cmd`;
    my $retCode = $? >> 8;
    if( $retCode!=0 ){
      Logging::warning( "Cannot resume domain  '$domain' (ErrorCode: $retCode, STDOUT:$ret) [Error:$!].",'UtilityError' );
      Logging::warning( "The domain '$domain' may be inaccessible after backup. Please, resume it manually!" ,'UnsuspendFailed');
    }
    $self->{suspendedDomain} = undef;
  }
}

1;
