# Copyright (C) 2005 FishGrove Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: recv_mail_ack.pm,v 1.1 2006/03/07 14:39:10 slash5234 Exp $

package Affelio::App::Standalone::Public::Bin::recv_mail_ack;
{
    use strict;

    use lib("../../../../../../extlib/");
    use lib("../../../../../../lib/");
    use Affelio::misc::CGIError;
    use Affelio::misc::Debug qw(debug_print);

    use Exporter;
    @Affelio::App::Standalone::Public::Bin::recv_mail_ack::ISA = "Exporter";
    @Affelio::App::Standalone::Public::Bin::recv_mail_ack::EXPORT = qw (run);

    #######################################################################
    #run
    #######################################################################
    sub run{

use CGI qw(-unique_headers);
$CGI::DISABLE_UPLOADS = 1;
$CGI::POST_MAX = 102_400;
use CGI::Session; #qw(-ip_match);
use HTML::Template;
use File::Copy;
use Crypt::DH;
use Error qw(:try);

use Affelio;
use Affelio::misc::MyCrypt;
use Affelio::SNS::Handshaker_c;
use Affelio::SNS::Handshaker_tmpDB;
use Affelio::exception::Exception;
use Affelio::exception::IOException;
use Affelio::misc::WebInput;

my $q = new CGI;

############################################################################
#Load Affelio
my $cfg_dir = "../config/";
my $af;
try{
    $af = new Affelio(ConfigDir => $cfg_dir);
}catch Error with{
    my $e = shift;
    error($q, "Affelio load error.\n" . $e);
};
my $wi = new Affelio::misc::WebInput;

############################################################################
#Sesion check (as admin)
my $sid = $q->cookie("affelio-$af->{user__nickname}");
my $session = new CGI::Session(undef, 
			       $sid, 
			       {Directory=> $af->{site__session_dir}});

my $TMPL_FILE="";
if( (!$session) || ($session->param("type") ne "self")  ){
    # Is the session alive?
    # Is the user the admin of this site?
    # if not....
    debug_print("StandAlone::recv_mail_ack.cgi: login is needed.");

    $TMPL_FILE 
	= "$af->{site__tmpl_dir}/owner_side/login.tmpl";
    my $tmpl = new HTML::Template( filename => $TMPL_FILE,
				   die_on_bad_params => 0);
    $tmpl->param(reason_msg => "You haven't been authenticated.");
    $tmpl->param("tmpl_path" => "$af->{site__tmpl_web_path}/owner_side/");
    print "Content-type: text/html; charset=UTF-8\n\n";
    print $af->translate_templateL10N($tmpl->output);
    exit(1);
}
debug_print("StandAlone::recv_mail_ack.cgi: Session as the admin is OK.");


############################################################################
#Read CGI input
my $session_id="";
$session_id = $wi->PTN_word($q->param("id"));
if(!$session_id){
    die "id is not defined. [$session_id]";
}
debug_print("StandAlone::recv_mail_ack: $session_id\n");


############################################################################
#Read temporarily-saved session
my $dummy;
my $timestamp;
my $peer_af_id;
my $peer_name;
my $peer_nickname;
my $peer_DH_pub_key_str;
my $peer_DH_pub_key;

############################################################################
#remove a record from tmpDB
my $tmpdb= new Affelio::SNS::Handshaker_tmpDB($af);
my @ret= $tmpdb->remove_received_Handshake($session_id);

if(!defined(@ret)){
    #No such session exists!!
    debug_print("StandAlone::recv_mail_ack: session not found.\n");
    error($q, "Affelio load error.\nNo such session exists!");
}else{
    ($dummy, $timestamp, $peer_af_id, 
     $peer_nickname, $peer_DH_pub_key_str) = @ret;

    $peer_DH_pub_key = Math::BigInt->new($peer_DH_pub_key_str);
}
debug_print("StandAlone::recv_mail_ack: $session_id, $timestamp, $peer_af_id, $peer_nickname, $peer_DH_pub_key_str\n");

############################################################################
#DH key generation
my $mydh = Crypt::DH->new;
#RFC 2412 - The OAKLEY Key Determination Protocol
#Group 1:  A 768 bit prime
my $DH_g="2";
my $DH_p="1552518092300708935130918131258481755631334049434514313202351194902966239949102107258669453876591642442910007680288864229150803718918046342632727613031282983744380820890196288509170691316593175367469551763119843371637221007210577919";
$mydh->g($DH_g);
$mydh->p($DH_p);
#
#Step (1):  create my public_key
$mydh->generate_keys;
my $my_DH_pub_key = $mydh->pub_key;
my $my_DH_pub_key_str = $mydh->pub_key->bstr;


############################################################################
#send FriendshipReply 
my $ret="";
try{
    $ret = reply_HandShake(dest_uri => "$peer_af_id",
			   timestamp => $timestamp,
			   my_nickname => $af->{user__nickname},
			   my_domain => $af->{user__domain},
			   my_AFID => $af->{site__user_afid},
			   DH_pub_key_str => $my_DH_pub_key_str
			   );
}catch Error with {
    my $E = shift;
    error($q, "HandShake reply output an error!\n$E");
};

debug_print("StandAlone::recv_mail_ack: reply_HandShake finished.");

############################################################################
#generate Password
my $pass = $mydh->compute_key($peer_DH_pub_key)->bstr;
debug_print("StandAlone::recv_mail_ack: PASSWORD=[$pass]\n");

############################################################################
#Add peer to my friends list.
try{
    $af->getFM->add_friend($peer_af_id, 
			  $peer_nickname,
			  $timestamp,
			  $pass);
}catch Error with{
    my $E = shift;
    error($q, "Error from FriendManager\n$E\n");
};
debug_print("StandAlone::recv_mail_ack: added to my friends list.");
sleep(2);

############################################################################
#Get peer's friends list.
try{
    $ret = get_F2List(dest_uri =>  "$peer_af_id",
		      timestamp => 0);
}catch Error with {
    my $E = shift;
    error($q, "HandShake was successful!\n But, get_F2List reply output an error!\n$E");
};
debug_print("StandAlone::recv_mail_ack: get_F2List finished.");
debug_print("StandAlone::recv_mail_ack: List I've got is [$ret]");
#
#
##################################################
#Save the F2 list into my DB
#$af->{fm}->save_F2List($ret, $peer_af_id);

my $urlencoded_title = url_encode($af->translate_templateL10N('<AF_M text="_HandshakeReply_SentBack_message_title">'));

############################################################################
#print output HTML
my $TMPL_FILE = "$af->{site__tmpl_dir}/owner_side/mail_ack_recved.tmpl";
my $tmpl = new HTML::Template( filename => $TMPL_FILE);
$tmpl->param(peer_af_id => $af->{site__user_afid} . "/outgoing.cgi?dest=".$peer_af_id);
$tmpl->param(peer_nickname => $peer_nickname);

$tmpl->param(next_url => $af->{site__user_afid} . "/admin.cgi?mode=messages&action=compose&to_url=" . $peer_af_id . "&title=" . $urlencoded_title);

$tmpl->param("tmpl_path" => "$af->{site__tmpl_web_path}");

print "Content-type: text/html; charset=UTF-8\n\n";
print $af->translate_templateL10N($tmpl->output);


	
    }#method

}
1;
