#!/usr/bin/perl -I.

###############################################################################
#
# chao.cgi
#
# Dreamcast version
# SONIC ADVENTURE
# Chao data portion
#  Point Cookie
#
#
###############################################################################

use strict;

use CGI;
use	DC;
use DB;


## Set up variables
use vars	(	'$dc',	# DC object
				'@BINDATA',
				'$errorURL',
				'$mailprog',
				'$CHAONAME',
				'@mail_a', '@mail_b', '@mail_c', '@mail_d', '@mail_e', '@mail_f', '@mail_g',
				'@chara', '@char', '@chaotype', '@nemuke', '@hara', '@suki', '@garden', '@Jewel'
			);

require 'evaluation.pl';

#...............................................

	my $q = new CGI;
	$dc = new DC($q);
	$errorURL = "chao_gardens.html";
	$mailprog = '/usr/lib/sendmail';

	@BINDATA = ();

    &check_data;

	my $where = $dc->q->cookie('chao');

    if($where eq 'daycare') {
        &daycare_check;
        $dc->output_form("html/chao_daycare_form.html");
    } elsif($where eq 'evaluation') {
        &evaluation;
        &chaomail;
		$dc->output_form("html/chao_evaluation_report.html");
    } elsif($where eq 'chaorace') {
        $dc->output_form("html/chao_race_form.html");
    } elsif($where eq 'torihiki') {
        $dc->output_form("html/torihiki.html");
    } else {
        $dc->error("A wrong cookie of \"$where\" was given.<BR>Please make sure your Dreamcast clock is correct.", $errorURL);
    }

exit(0);

#--------------------------------------------------------
# Data Check
#--------------------------------------------------------
sub check_data {
	my $MAIL = "";
	my ($dbh, $errN, $errstr, @row);
	my $key = "";

    # Data Decode
    if( &decode($dc->q->param('chaodata')) != 0) {
        $dc->error("Something wrong with your Chao data.<BR>Please recreate the Chao upload file and try again.", $errorURL);
    }

    # Key Acquisition
    $MAIL = $dc->q->param('mailid');
    $MAIL =~ y/A-Z/a-z/;
	$dc->q->param('mailid', $MAIL);
    if($MAIL eq "" || $MAIL !~ /[A-Za-z0-9_][-A-Za-z0-9:\._%]*@[-A-Za-z0-9][-A-Za-z0-9\.]*[-A-Za-z0-9]\.[A-Za-z0-9][-A-Za-z0-9\.]*[A-Za-z0-9]/) {
        $dc->error("Something wrong with E-mail address \"$MAIL\".<BR>Please make sure there are no spaces at the end of your E-mail address.", $errorURL);
    }

    # Hardware ID decode - Not Used
    # &decode_hwid(substr($dc->q->param('dcid'),0,12));

	# Read user information from the table
	$key = $dc->get_key($MAIL);

	if ($key ne "")
	{
		($dbh, $errstr) = DB::openOracleConnection();
		if( !$dbh )
		{
			$dc->error("[chao] Error connecting to database: $errstr", $errorURL);
		}

		($errN, $errstr, @row) = DB::getRow_UserByUK( $dbh, $dc->DBaseTable('USER'), $key );
		if ($errN)
		{
			$dc->error("[chao] Fetching user key: $errN .... $errstr", $errorURL);
		}

		DB::closeOracleConnection( $dbh );

		$dc->q->param('NAME', $row[$dc->UserOff('NAME')]);		# Name
		$dc->q->param('CITY', $row[$dc->UserOff('CITY')]);		# City
		$dc->q->param('STATE', $row[$dc->UserOff('STATE')]);	# State
		$dc->q->param('COUNTRY', $row[$dc->UserOff('COUNTRY')]);# Country
		$dc->q->param('MAIL', $row[$dc->UserOff('MFLAG')]);		# Message Flag
	}
	else
	{
		$dc->q->param('NAME', "");		# Name
		$dc->q->param('CITY', "");		# City
		$dc->q->param('STATE', "");		# State
		$dc->q->param('COUNTRY', "");	# Country
	}

	# Set default to No
	if ($dc->q->param('MAIL') ne 'Y')
	{
		$dc->q->param('MAIL', 'N');
	}
}

sub daycare_check {
    # Special Chao Check
    if($BINDATA[68] == 6) {
        # Special Chao
        &output_message("This Chao is very precious.<BR>So we can't accept it.<BR>Please take good care of it.<BR>", $errorURL);
        exit;
    }
    if((($BINDATA[68+54] & 64) != 0) || (($BINDATA[68+54] & 128) != 0)) {
        # Chao for download
        &output_message("This Chao is specifically for downloading.<BR>It isn't possible for us to accept it.<BR>Please take good care of it.<BR>", $errorURL);
        exit;
    }
}

#------------------------------------------------
# Decode
#------------------------------------------------
sub decode {
    my $srcdata = shift;

	my $errorNum = 0;
	my $CHAONAME = "";
	my ($i, $j, $val, $val2);
    
	my (@XOR_CODE) = (65,84,69,90);     # 0x5A455441
    my (@PLUS_VAL) = (65,78,65,78);     # 0x4E414E41

    # BASE64Decode
    @BINDATA = $dc->decode_base64($srcdata);

    my @tmp_val = (0,0,0,0);
    for($i=0;$i<145;$i++) {
        my $tmp_val2 = 0;
        for($j=0;$j<4;$j++) {
            $BINDATA[$i*4+$j] ^= ($tmp_val[$j] ^ $XOR_CODE[$j]);
            $tmp_val[$j] = ($tmp_val[$j] + $PLUS_VAL[$j] + $tmp_val2);
            $tmp_val2 = $tmp_val[$j]>>8;
            $tmp_val[$j] &= 255;
        }
    }
 
    my $CRC = ($BINDATA[1]<<8)+$BINDATA[0];
    # if($CRC != $dc->crc(\@BINDATA)) {
        # $dc->error("CRC Check Error!<BR>Chao data is corrupted.", $errorURL);
		# $errorNum = 1;
    # }

    # Flag eliminated automatically when file is downloaded.
    $BINDATA[68+54] |= 32;

    my $DATA_ID = sprintf "%02X%02X%02X%02X",$BINDATA[7],$BINDATA[6],$BINDATA[5],$BINDATA[4];
    if($DATA_ID ne 'CDACB521') {
        $dc->error("Something wrong with Chao data.\"$DATA_ID\"", $errorURL);
		$errorNum = 1;
    }

	my $kanji = 0;
    for($i=72;$i<79;$i++)
	{
		$val = $BINDATA[$i];
		$val2 = $BINDATA[$i + 1];
		
		$j = $dc->convert_katakana($val, $val2, $CHAONAME);
		if ($j)
		{
			# Katakana was found, value contains loop skip value
			$kanji = 1;
			if ($j == 2)
			{
				# Two character combo so skip past two characters
				++$i;
			}
		}
		else
		{
			if (($kanji == 1) && ($dc->ChrCode($val) eq '-'))
			{
				# "-" Repeat the immediately preceding vowel.
				$CHAONAME .= substr($CHAONAME, -1, 1);
			}
			else
			{
				$CHAONAME .= $dc->ChrCode($val);
			}
		}
    }

	# Convert Chao name into HTML safe text
	if ($CHAONAME ne "")
	{
		$q->autoEscape(0);
		$dc->q->param('ChaoName', $dc->smut_check($CHAONAME));
		$q->autoEscape(1);
	}
	else
	{
		$dc->q->param('ChaoName', "YOUR CHAO");
	}

    return($errorNum);
}

#------------------------------------------------
# Message Output
#------------------------------------------------
sub output_message {
    my $msg = shift;
	my $URL = shift;

    print <<EOF;
Content-type: text/html

<html>
<head>
<title>
Sonic Adventure Online - Hints
</title>
<meta name="x-uirequest" content="urlbaroff">
<script LANGUAGE = "JavaScript">

<!--
        if (document.images) {
            img1on = new Image(); 
            img1on.src = "file:/button_back_on.gif";   
            img1off = new Image(); 
            img1off.src = "file:/button_back.gif"; 
        }

function imgOn(imgName) {
        if (document.images) {
            document[imgName].src = eval(imgName + "on.src");
        }
}

function imgOff(imgName) {
        if (document.images) {
            document[imgName].src = eval(imgName + "off.src");
        }
}

// -->

</script>
<bgsound src="file:/sonicadv/chao.adx">
</head>
<body x-marginleft=0 x-margintop=0   background="file:/bg_scroller.gif" bgcolor="#000000" marginheight=0 marginwidth=0 topmargin=0 leftmargin=0>
<center>
<img src="file:/blank_dot.gif" width=1 height=30 border=0 alt=""><br>
<table cellspacing=0 cellpadding=5 border=0 width=590><tr><td align=center valign=top bgcolor="#000033"><table cellspacing=0 cellpadding=0 border=0 width=580><tr><td align=left valign=top bgcolor="#ffffff">

<!-- HEADER IMAGE -->
<!-- choose from below... -->
<!-- header_chao_showoff.gif -->
<!-- header_events.gif -->
<!-- header_world_rankings.gif -->

<img src="file:/header_chao_daycare.gif" width=580 height=150 border=0 alt=""><br>

<!-- END HEADER IMAGE -->

<table cellspacing=0 cellpadding=0 border=0 width=580><tr><td align=left valign=top width="10">
<img src="file:/blank_dot.gif" width=10 height=1 border=0 alt="">
</td>
<td align=left valign=top width=560>

<!-- BEGIN CONTENT HERE -->
<P><CENTER>
$msg
</CENTER></P>
<!-- end content -->

<P>
<a href="http://sonic.games.dreamcast.com/$URL"  onMouseOver="imgOn('img1')" onMouseOut="imgOff('img1')"><img src="file:/button_back.gif" width=81 height=24 border=0 alt="" name="img1"></a><P>				
</td><td align=left valign=top width="10">
<img src="file:/blank_dot.gif" width=10 height=1 border=0 alt="">
</td>
</tr>
</table>
</tr>
</tr>
</table>
</td>
</tr>
</table>
<br>&nbsp;
</center>
</body>
</html>

EOF
}

#--------------------------------------------------------
# Evaluation
#--------------------------------------------------------
sub evaluation {
	my $CHAONAMEHTML = "";
	my ($i, $j, $val, $val2, $kanji);

    # Chao Type
    $dc->q->param('Joutai', $chaotype[$BINDATA[68]]);

    # Age
	my $age = int(($BINDATA[136]+($BINDATA[137]<<8)+($BINDATA[138]<<16)+($BINDATA[139]<<24))/60);
	if ($age == 0) {
		$dc->q->param('Nenrei', "Newborn");
	} else {
		$dc->q->param('Nenrei', sprintf "%d year old",$age);
	}

    # Sleepiness
    $dc->q->param('Nemuke', $nemuke[int($BINDATA[165]/50)]);

    # Hunger
    $dc->q->param('Manpuku', $hara[int($BINDATA[166]/50)]);

    # Affection
    $dc->q->param('Skinsip', sprintf "%d\%",int(($BINDATA[112]+($BINDATA[113]<<8))/10));

	# Swim Power
	$dc->q->param('Swim', int(($BINDATA[80]+($BINDATA[81]<<8))/10));

	# Flying Power
	$dc->q->param('Fly', int(($BINDATA[82]+($BINDATA[83]<<8))/10));

	# Running Power
	$dc->q->param('Run', int(($BINDATA[84]+($BINDATA[85]<<8))/10));

	# Power
	$dc->q->param('Power', int(($BINDATA[86]+($BINDATA[87]<<8))/10));

    # Comments
    my $chara = 0;
    my $val = -100;
    my $val2;
    for($i=0;$i<6;$i++) {
        $val2=$BINDATA[$i*2+176];
        if($val2 >= 128) {
            $val2 -= 256;
        }
        if($val<$val2) {
            $chara = $i;
            $val = $val2;
        }
    }

	$CHAONAMEHTML = "";
	$kanji = 0;
    for($i=72;$i<79;$i++) {
		$val = $BINDATA[$i];
		$val2 = $BINDATA[$i + 1];
		
		$j = $dc->convert_katakana($val, $val2, $CHAONAMEHTML);
		if ($j)
		{
			# Katakana was found, value contains loop skip value
			$kanji = 1;
			if ($j == 2)
			{
				# Two character combo so skip past two characters
				++$i;
			}
		}
		else
		{
			if (($kanji == 1) && ($dc->ChrCode($val) eq '-'))
			{
				# "-" Repeat the immediately preceding vowel.
				$CHAONAMEHTML .= substr($CHAONAMEHTML, -1, 1);
			}
			else
			{
				$CHAONAMEHTML .= $dc->ChrCode($val);
			}
		}
    }

	# Convert Chao name into HTML safe text
	if ($CHAONAMEHTML ne "")
	{
		$q->autoEscape(0);
		$dc->q->param('ChaoName', $dc->smut_check($CHAONAMEHTML)."\'S ");
		$q->autoEscape(1);
	}
	else
	{
		$dc->q->param('ChaoName', "");
	}

	$CHAONAME = "";
	$kanji = 0;
    for($i=72;$i<79;$i++) {
		$val = $BINDATA[$i];
		$val2 = $BINDATA[$i + 1];
		
		$j = $dc->convert_katakana($val, $val2, $CHAONAME);
		if ($j)
		{
			# Katakana was found, value contains loop skip value
			$kanji = 1;
			if ($j == 2)
			{
				# Two character combo so skip past two characters
				++$i;
			}
		}
		else
		{
			if (($kanji == 1) && ($dc->ChrCode($val) eq '-'))
			{
				# "-" Repeat the immediately preceding vowel.
				$CHAONAME .= substr($CHAONAME, -1, 1);
			}
			else
			{
				$CHAONAME .= $dc->ChrCodeText($val);
			}
		}
    }
	if ($CHAONAME ne "")
	{
		$CHAONAME = $dc->smut_check($CHAONAME);
	}

	my $favor = $chara[$chara];
	$dc->q->param('Chara', $favor);
	$dc->q->param('Favorite', "<img src=\"/images/favorite/$char[$chara]_small.gif\" width=50 height=50 border=0 hspace=5 align=\"left\">");

    $dc->q->param('Comment', sprintf "I like %s %s  I am having fun in %s!", $chara[$chara], $suki[int(($val+100)/70)], $garden[$BINDATA[69]]);

	# Jewels won count
	my $WIN = $BINDATA[120];
	my $awards = "";

	my (@mask) = (0x01, 0x02, 0x04, 0x08, 0x10);
	for ($i = 0; $i < 5; $i++)
	{
		if ($WIN & $mask[$i])
		{
			$awards .= "<img src=\"/images/jewels/$Jewel[$i].gif\" width=50 height=50 border=0 hspace=5 align=\"top\">";
		} else {
			$awards .= "<img src=\"/images/jewels/jewel_blank.gif\" width=50 height=50 border=0 hspace=5 align=\"top\">";
		}
	}
	$dc->q->param('Awards', $awards);
}

sub chaomail {
    my $val;
	my $MAIL;
	my $chara = $dc->q->param('Chara');
	my $email = $dc->q->param('mailid');

    # Send mail
    if(open(MAIL, "|$mailprog $email")) {
        # Header output
        print MAIL "From: daycare\@sonic-adventure.com\n";
        print MAIL "Reply-to: daycare\@sonic-adventure.com\n";
		if ($CHAONAME ne "")
		{
			print MAIL "Subject: $CHAONAME\'s Chao heart\n\n";
		}
		else
		{
			print MAIL "Subject: Chao\'s heart\n\n";
		}

        # Body output
        srand(time|$$);

		if ($dc->q->param('NAME') ne "")
		{
			print MAIL "Hi ".$dc->q->param('NAME')."!\n\nHow's the weather in ";
			print MAIL $dc->q->param('CITY').", ";
			if ($dc->q->param('STATE') ne "") {
				print MAIL $dc->state_name($dc->q->param('STATE')).", ";
			}
			print MAIL $dc->country_name($dc->q->param('COUNTRY'))."?\n\n";
		}
		else
		{
			print MAIL "Hi!\n\n";
		}
        # Part A
        $val=int(rand()*7);
        print MAIL "Chao weather report!  $mail_a[$val] in $garden[$BINDATA[69]]!\n";
        # Part B
        $val=int(rand()*8);
        print MAIL "With scattered $mail_b[$val]!\n\n";
        # Part C
        $val=int(rand()*10);
        print MAIL "I got evaluated today!  $mail_c[$val]\n";
        # Part D
        $val=int(rand()*10);
        print MAIL "$mail_d[$val]\n\n";
        # Part E
        $val=int(rand()*10);
        print MAIL "By the way, $chara $mail_e[$val]\n\n";

		# Part F
		if ($CHAONAME ne "")
		{
			$val=int(rand()*5);
			print MAIL "$mail_f[$val]\n$CHAONAME\n\n";
		}

        # Part G
        $val=int(rand()*10);
        print MAIL "PS: " . $mail_g[$val];

        close(MAIL);
    } else {
		$dc->error("Unable to send e-mail to $dc->q->param('mailid').", $errorURL);
	}
}

#------------------------ EOF --------------------------
