#! /usr/bin/perl
# This script will cleanup any stale sessions the Portal system has created.

# portal_accounting_cleanup - Created by James Pattie, (james@pcxperience.com)
# Copyright (c) 2000-2002, Xperience, Inc. (http://www.pcxperience.com/)
# 01/19/2001

use DBIWrapper;
use Portal::Language;
use Portal::Data::Config;
use Portal::Log;
use Portal::Methods;
use Portal::Accounting::DB::Main;
use Portal::Application;
use strict;
my $debug = 0;

my $langObj = Portal::Language->new(lang => 'en');
if ($langObj->didErrorOccur)
{
  die "Error instantiating Portal::Language->new()!  Error = " . $langObj->errorMessage() . "\n";
}

my $configObj = undef;
eval { $configObj = Portal::Data::Config->new(langObj => $langObj); };
if ($@)
{
  die "Instantiating Portal::Data::Config failed!\n$@";
}

my $methods = Portal::Methods->new(langObj => $langObj);
if ($methods->didErrorOccur)
{
  myDie(error => $methods->errorMessage, configObj => $configObj);
}

# make connection to the portal database
my $portalDB = $methods->portalDBSetup(type => "portal", configObj => $configObj);
if ($methods->didErrorOccur)
{
  myDie(error => $methods->errorMessage . "\n", configObj => $configObj);
}
if ($portalDB->didErrorOccur)
{
  myDie(error => $portalDB->errorMessage, configObj => $configObj);
}

# make an instance of the Application Object.
my $appObj = Portal::Application->new(portalDB => $portalDB, langObj => $langObj);
if ($appObj->didErrorOccur)
{
  myDie(error => $appObj->errorMessage, configObj => $configObj);
}

# now get the information about ourselves in the portal. (Our app id, etc.)
my $appInfoObj = $appObj->getApplicationInfo(name => "Accounting");
if (!defined $appInfoObj)
{
  if ($appObj->didErrorOccur)
  {
    myDie(error => $appObj->errorMessage, configObj => $configObj);
  }
  else
  {
    myDie(error => "Application 'Accounting' does not exist!\n", configObj => $configObj);
  }
}
else
{
  if ($appObj->didErrorOccur)
  {
    myDie(error => $appObj->errorMessage, configObj => $configObj);
  }
}

# now get a list of all CompanyApplicationObjects that are for this app/server combo.
my @apps = $appObj->getCompanyAppsForServer(serverName => $configObj->{myHostName}, appObj => $appInfoObj);
if ($appObj->didErrorOccur)
{
  myDie(error => $appObj->errorMessage, configObj => $configObj);
}

if (scalar @apps == 0)
{
  myDie(error => "There are no companies configured to use the 'Accounting' app on server '$configObj->{myHostName}'!\n", configObj => $configObj);
}
# work with the entries returned
foreach my $companyAppObj (@apps)
{
  if ($debug)
  {
    print "Company with id = '$companyAppObj->{companyId}', Database Name = '$companyAppObj->{dbName}'\n";
  }

  # now make a connection to the database.
  my $accountDB = DBIWrapper->new(dbType => $companyAppObj->dbType, dbHost => $companyAppObj->dbHost, dbName => $companyAppObj->dbName, dbUser => $configObj->dbUser, dbPasswd => $configObj->dbPasswd, dbPort => $companyAppObj->dbPort);
  if ($accountDB->didErrorOccur)
  {
    myDie(error => $accountDB->errorMessage, configObj => $configObj);
  }

  # instantiate an instance of Accounting::DB::Main to do the actual dirty work for us.
  my $dbMain = Portal::Accounting::DB::Main->new(dbHandle => $accountDB, langObj => $langObj);
  if ($dbMain->didErrorOccur)
  {
    myDie(error => $dbMain->errorMessage, configObj => $configObj);
  }

  # validate we are at least a 1.2+ database.
  my $dbVersion = $dbMain->getDBVersion;
  if ($dbMain->didErrorOccur)
  {
    myDie(error => $dbMain->errorMessage, configObj => $configObj);
  }
  if ($dbVersion < 1.2)
  {
    myDie(error => "The database is at version '$dbVersion' which is too old to be portal aware!\nIt needs to be at least 1.2!\n\n", configObj => $configObj);
  }

  # now check and see if we have any temporary report files to cleanup.
  my @files = $dbMain->getTempFilesToCleanup; # default to 3 hours - specify timeLength and timeValue to override.
  if ($dbMain->didErrorOccur)
  {
    myDie(error => $dbMain->errorMessage, configObj => $configObj);
  }

  if ($debug)
  {
    print "Cleaning up '" . scalar (@files) . "' files...\n";
  }
  if (scalar @files > 0 && !$debug)  # only display if cleaning up files and debug is turned off.
  {
    print "Company with id = '$companyAppObj->{companyId}', Database Name = '$companyAppObj->{dbName}'\n";
    print "Cleaning up '" . scalar (@files) . "' files...\n";
  }
  foreach my $fileName (@files)
  {
    print "file = '$fileName': ";
    my $result = $dbMain->cleanupTempFile(fileName => $fileName);
    if ($dbMain->didErrorOccur)
    {
      myDie(error => $dbMain->errorMessage, configObj => $configObj);
    }
    if ($result == -1)
    {
      print "didn't exist on disk anymore (but was successfully removed from database)!\n";
    }
    elsif ($result == -2)
    {
      print "didn't exist in the database anymore (but was successfully deleted from disk)!\n";
    }
    elsif ($result == -3)
    {
      print "doesn't exist on disk or in the database!\n";
    }
    else
    {
      print "Cleaned up OK\n";
    }
  }
}

exit 0;

# myDie - Takes lang, encoding, error, configObj
sub myDie
{
  my %args = ( lang => 'en', encoding => 'iso-8859-1', error => "", configObj => undef, @_ );
  my $lang = $args{lang};
  my $encoding = $args{encoding};
  my $message = $args{error};
  my $configObj = $args{configObj};
  my $dateStamp = `/bin/date`;
  chomp $dateStamp;

  print("Error Occurred!\n");
  print($message);
  print("Have the Administrator check the error log ($dateStamp).\n");
  my $logObj = Portal::Log->new(dbHandle => $portalDB, langObj => $langObj);
  if ($logObj->didErrorOccur)
  {
    die $logObj->errorMessage;
  }
  my $hostname = `hostname -i`;
  chomp $hostname;
  $hostname =~ s/ //g;

  my $logEntry = Portal::Objects::LogEntry->new(action => 20, ipAddress => $hostname, extraInfo => $message, userId => 0, langObj => $langObj);
  if ($logEntry->didErrorOccur)
  {
    die $logEntry->errorMessage;
  }
  $logObj->newEntry(logEntry => $logEntry);
  if ($logObj->didErrorOccur)
  {
    die $logObj->errorMessage;
  }
  exit 1;
}
