#!/usr/bin/perl 

use strict;

use CGI qw(-unique_headers);
use Cwd;
use DBI;
use lib("./extlib");
use HTML::Template;
use Error qw(:try);
use lib("./lib");
use Affelio;
use Affelio::misc::Debug qw(debug_print);

############################################################################
#Main
############################################################################
my $g_username="";
my $g_password="";
my $g_nickname="";
my $g_email="";
my $q = new CGI;
my $g_fsroot = cwd();
my $g_webroot = $q->self_url();

#########################################################################
#1st screen
#########################################################################
if($q->url_param("mode") ne "go"){
    print "Content-type: text/html; charset=UTF-8\n";
    print "Pragma: no-cache", "\n\n"; 
    print <<EOM;
<HTML>
<h1>Affelio Upgrade Script</h1>
<P>
<H2>1. Copy your affelio.cfg to config/affelio.cfg</H2>
Location of <B>affelio.cfg</B> file changed. Create <B>config/</B> 
directory and move <b>affelio.cfg</b> to <B>config/</B> directory.
<P>
<H2>2. Upgrade your Affelio data</H2>
Push the button below and upgrade your data!
<P>
<FORM ACTION="upgrade.cgi?mode=go" method=POST>
<INPUT TYPE="submit" VALUE="Upgrade">
</FORM>
</HTML>
EOM
exit(1);


#########################################################################
#Do upgrade
#########################################################################
}else{
    print "Content-type: text/html; charset=UTF-8\n";
    print "Pragma: no-cache", "\n\n"; 

    ################################
    #Start Affelio
    ################################
    my $af;
    try{
	$af = new Affelio(ConfigDir => "./config/",
			  Mode => "init");
    }catch Error with{
	my $e = shift;
	print("Affelio load error.\n" . $e->stacktrace);
	exit(1);
    };

    ################################
    #Create application table
    ################################
    {
	my $query = 'SELECT * from AFuser_CORE_apps';
        my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    print "We confirmed that the app table does not exist.<BR>";
	    print "So, We will make it<BR>";
	    my $query = <<EOT;
CREATE TABLE AFuser_CORE_apps(appid INTEGER PRIMARY KEY AUTOINCREMENT, 
			      install_name TEXT, 
			      install_title TEXT,
			      app_URI TEXT,
			      app_name TEXT,
			      app_version TEXT,
			      app_desc TEXT,
			      app_author TEXT,
			      guest_index TEXT,
			      owner_index TEXT,
			      action_types TEXT,
			      action_types_desc TEXT)
EOT
            my $sth;
	    eval{
		$sth = $af->getDB->prepare($query);
		$sth->execute;
	    };
	    if($@){
		print 'Error occured in creating the table<BR><BR>' .  $@;
		exit(1);
	    }

	}else{
	    #Application table already exists.
	    #So, do nothing.
	    print 'We confirmed that the app table already exists.<BR>';
	    print 'So, We will do nothing.<BR>';
	}
    }#block

    ################################
    #Create nghr_news
    ################################
    {
	my $query = 'SELECT * from AFuser_CORE_nghr_news';
        my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    print "We confirmed that nghr_news table does not exist.<BR>";
	    print "So, We will make it<BR>";
	    my $query = <<EOT;
CREATE TABLE AFuser_CORE_nghr_news(nid INTEGER PRIMARY KEY AUTOINCREMENT, 
				   datetime INTEGER,
				   af_id TEXT,
				   nickname TEXT,
				   app_install_name TEXT,
				   title TEXT,
				   description TEXT,
				   creator TEXT,
				   URL TEXT)
EOT
            my $sth;
	    eval{
		$sth = $af->getDB->prepare($query);
		$sth->execute;
	    };
	    if($@){
		print 'Error occured in creating the table<BR><BR>' .  $@;
		exit(1);
	    }

	}else{
	    #Application table already exists.
	    #So, do nothing.
	    print 'We confirmed that nghr_news table already exists.<BR>';
	    print 'So, We will do nothing.<BR>';
	}
    }#block

    ################################
    #Create my_news
    ################################
    {
	my $query = 'SELECT * from AFuser_CORE_my_news';
        my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    print "We confirmed that my_news table does not exist.<BR>";
	    print "So, We will make it<BR>";
	    my $query = <<EOT;
CREATE TABLE AFuser_CORE_my_news(nid INTEGER PRIMARY KEY AUTOINCREMENT, 
				   datetime INTEGER,
				   app_install_name TEXT,
				   title TEXT,
				   description TEXT,
				   creator TEXT,
				   URL TEXT)
EOT
            my $sth;
	    eval{
		$sth = $af->getDB->prepare($query);
		$sth->execute;
	    };
	    if($@){
		print 'Error occured in creating the table<BR><BR>' .  $@;
		exit(1);
	    }

	}else{
	    #Application table already exists.
	    #So, do nothing.
	    print 'We confirmed that my_news table already exists.<BR>';
	    print 'So, We will do nothing.<BR>';
	}
    }#block

    ################################
    #Add columns to friend tale
    ################################
    add_column($af, 'AFuser_CORE_friends', 'last_news_in', "INTEGER", 0);
    add_column($af, 'AFuser_CORE_friends', 'last_news_out', "INTEGER", 0);
    #
    add_column($af, 'AFuser_CORE_friends', 'last_access', "INTEGER", 0);
    add_column($af, 'AFuser_CORE_friends', 'count_access', "INTEGER", 0);
    #
    add_column($af, 'AFuser_CORE_friends', 'last_incoming', "INTEGER", 0);
    add_column($af, 'AFuser_CORE_friends', 'count_incoming', "INTEGER", 0);
    #
    add_column($af, 'AFuser_CORE_friends', 'last_outgoing', "INTEGER", 0);
    add_column($af, 'AFuser_CORE_friends', 'count_outgoing', "INTEGER", 0);
    #
    add_column($af, 'AFuser_CORE_friends', 'apps', "TEXT", "' '");

    ################################
    #Create small images
    ################################
    print "We will make resized profile images...";
    eval{
	require Affelio::misc::ImageEditor;
	Affelio::misc::ImageEditor::resize_image("$af->{site__user_dir}/profile_face.jpg", "$af->{site__user_dir}/profile_face_100x100.jpg", 100);
	Affelio::misc::ImageEditor::resize_image("$af->{site__user_dir}/profile_face.jpg", "$af->{site__user_dir}/profile_face_150x150.jpg", 150);
    };
    if($@){
	print 'Error occured in creating resized images...<BR><BR>' .  $@;
	exit(1);
    }

    print "Done.<BR>";

    print '<h2>OK. Successfuly done.</H2><P><B>Delete this CGI immediately!!</B>';
    exit(1);
}



sub add_column{
    my $af= shift;
    my $table = shift;
    my $col = shift;
    my $type = shift;
    my $def = shift;

    my $query = "SELECT $col from $table";
    my $sth;
    eval{
	$sth = $af->getDB->prepare($query);
	$sth->execute;
    };
    if($@){
	print "We confirmed that table [$table] needs column [$col]<BR>";
	my $query2 = "ALTER TABLE $table ADD COLUMN $col $type DEFAULT $def";
	my $sth;
	eval{
	    $af->getDB->do($query2);
	};
	if($@){
	    print 'Error occured in modifying the table<BR><BR>' .  $@;
	    exit(1);
	}
	print "Successfully added [$col].<BR>";
	
    }else{
	#Application table already exists.
	#So, do nothing.
	print "We confirmed that table [$table] already has [$col]<BR>"; 
	print 'So, We will do nothing.<BR>';
    }
}
