package SB::Migration;

use strict;
use SB::Logging qw($Logger ERROR INFO WARNING DEBUG FATAL);
use SB::Defaults qw($SB_PREFIX $CONFIG);
use SB::Utils qw(run);
use SB::DB;

use vars qw($VERSION);
$VERSION        =  4.00;
use Exporter;
use vars qw(@ISA @EXPORT @EXPORT_OK);
@ISA = qw(Exporter);

use subs qw(performMigration getSBVersionFromDB migrateAllSites migrate);

BEGIN {
    @EXPORT    = qw();
    @EXPORT_OK = qw(performMigration);
}

sub getSBVersionFromDB() {
	my $dbh = SB::DB::getSBHandle();
    my $sth = $dbh->prepare("select value from config_param where name='version'") || return;
    $sth->execute() || return;
    my $row = $sth->fetchrow_hashref() || return;
    my $version = $row->{'value'};
    $sth->finish();
    $dbh->disconnect();
    return $version;
}

sub performMigration() {
	unless (open(MIGRATE, "<$SB_PREFIX/migrate")) {
		$Logger->Log(ERROR, "Migration failed: unable to determine previous version");
		return 1;
	}
	my $version = <MIGRATE>;
	#chomp $version;
	close(MIGRATE);
	
	# Some undefined 3.x version, get version from database
	if ($version =~ m#3\.X\.X#) {
		$version = getSBVersionFromDB();
		if ($version) {
			# Put version back to 'migrate' file for migration.php
			open(MIGRATE, ">$SB_PREFIX/migrate");
			print MIGRATE $version;
			close(MIGRATE);
		}
		else {
			$Logger->Log(ERROR, "Migration failed: unable to determine previous version");
			return 1;
        }
	}
	my $status = migrate();
	if ($status == 0) {
		$Logger->Log(INFO, "Migration process has finished");
	} else {
		$Logger->Log(WARNING, "Migration process has finished with errors");
	}
	return 0;
}

sub migrate {
	my $phpcli_path = $CONFIG->{"internal"}->{"phpcli_path"};
    $Logger->Log(INFO, "Migration process started");

	my ($output, $code) = run("$phpcli_path -q $SB_PREFIX/utils/migration.php");
    return $code;
}

sub migrateAllSites {
	my $phpcli_path = $CONFIG->{"internal"}->{"phpcli_path"};;
	$Logger->Log(INFO, "Migrating sites.");
	my $code;

	open (F, "$phpcli_path -q $SB_PREFIX/utils/migration.php --migrate-all-sites 2>&1 | ") ||
				$Logger->Log(FATAL, "Failed to start migration script: $!");

	while (<F>) {
		$Logger->Log(INFO, $_);
	}
	close(F); 
	$code = $? >> 8;
	SB::Utils::changeOwner($CONFIG->{'internal'}->{'httpd_owner'});
	return $code;
}

1;

