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

use strict;
eval{require warnings;1;};


use PleskVersion;
use SiteApp::SiteApp;
use SiteApp::SiteApp10;
use SiteApp::SiteAppSmb;
use SiteApp::SiteAppGlobalSettings;

sub getServerSettingsForApplications {  
  if ( PleskVersion::atLeast( 10, 3, 0 ) ) {
    return map { SiteApp::SiteAppGlobalSettings->new($_) } SiteApp::SiteAppGlobalSettings::getSappsGlobalSettings() ;
  }
}

sub getDomainSiteapps {
  my ($dom_id, $dbh) = @_;
  # Site applications migration is supported since Plesk 7.0.0
  if ( PleskVersion::atLeast( 10, 0, 0 ) ) {
    return _getDomainSiteapps10($dom_id);
  }
  else {
    return _getDomainSiteapps($dom_id, $dbh);
  }
  return;
}

sub _getDomainSiteapps10 {
  my ($webspaceId) = @_;

  my $sappInstancesUtil; # default to \&SiteApp::SiteApp10::getSappsInstancesUtil
  if ( PleskVersion::isSmb() ) {
    $sappInstancesUtil = \&SiteApp::SiteAppSmb::getSappsInstancesUtil;
  }

  return map { SiteApp::SiteApp10->new($_) } SiteApp::SiteApp10::getSappMetas($webspaceId, $sappInstancesUtil) ;
}

sub _getDomainSiteapps {
  my ( $dom_id, $dbh ) = @_;

  my @SiteApplications;
  my @sapp_ids;

  # ids of site apps installed on domain
  my $sql = "SELECT id FROM SiteApps WHERE dom_type='domain' AND dom_id='$dom_id'";
  if ( $dbh->execute_rownum($sql) ) {
    while ( my $idRow = $dbh->fetchrow() ) {
      push @sapp_ids, $idRow->[0];
    }
  }
  $dbh->finish();

  # subdomains
  $sql = "SELECT id FROM subdomains WHERE dom_id=$dom_id";
  my (@subdoms);
  if ( $dbh->execute_rownum($sql) ) {
    while ( my $subdomRow = $dbh->fetchrow() ) {
      push @subdoms, $subdomRow->[0];
    }
  }
  $dbh->finish();

  # ids of site apps installed on subdomains
  foreach my $subdom_id (@subdoms) {
    $sql = "SELECT id FROM SiteApps WHERE dom_type='subdomain' AND dom_id='$subdom_id'";
    if ( $dbh->execute_rownum($sql) ) {
      while ( my $idRow = $dbh->fetchrow() ) {
        push @sapp_ids, $idRow->[0];
      }
    }
    $dbh->finish();
  }

  foreach my $sapp_id (@sapp_ids) {
    my $sapp = SiteApp::SiteApp->new( $sapp_id, $dbh );
    if ( $sapp->error() ) {
      my $sapp_prefix = $sapp->getInstallPrefix(); 
      my $details = $sapp->error();
      Logging::warning("Cannot dump site app with id '$sapp_id'" . (defined $sapp_prefix ? " and prefix '$sapp_prefix'"  : "") . ". "
                     . "However, all the app-related content should be transferred correctly. [$details]", 'SiteappError');
      next;
    }
    push @SiteApplications, $sapp;
  }

  return @SiteApplications;
}



1;
