#!/usr/bin/perl

use MIME::Base64;
use Jcode;
use Pg;
use File::Path;
use Image::Magick;

$pn="naopic";
$uplpath="/home/h0/naoto/public_html/mobup/htdocs/archive";
$dbname = "naoto";
$dbuser = "naoto";
$dbpw = "9513nnn7010";
$conn = Pg::connectdb("dbname=$dbname host=localhost " . 
                     "user=$dbuser password=$dbpw");

$flag=0;
$fn=time . "_" . $$;
$fnorg=$fn;

open(FH,">>/home/h0/naoto/public_html/mobup/lib/cached/" . $fnorg . ".txt");

while (<>){
    print FH $_;
#    if (/^Subject: PN:/){@tmp=split(/:/,$_); $pn=$tmp[2];chomp($pn);}
    
    if (/^From: /){
	@tmp=split(/: /,$_); $email=$tmp[1];
	if ($email=~/</){$email=$'; $email=~s/>//g;}  #'
	chomp($email);
	$sql="select mobuid from mobusers where email ='" . $email . "';";
	$res=$conn->exec($sql);
	if ($res->ntuples==1){
	    $uid=$res->getvalue(0,0);
	}
    }
    if (/^-+=_NextPart_/ || /^-+[a-zA-Z0-9]+/){$flag=$flag+1;}
    if ($flag>0){
#	if (/name="/){
#	    @tmp = split(/\./,$_);
#	    $tmp[1]=~s/"//g;
#	    chomp($tmp[1]);
#	    if ($tmp[1]) {
#		$b[$flag]=$tmp[1];
#	    }
#	}
	if (/text\/plain/){$b[$flag]="txt";}
	elsif (/image\/gif/){$b[$flag]="gif";}
	elsif (/image\/jpeg/){$b[$flag]="jpg";}
	elsif (/image\/bmp/){$b[$flag]="bmp";}
	elsif (/image\/png/){$b[$flag]="png";}
	elsif (/video\/mp4/){$b[$flag]="mp4";}
	elsif (/video\/3gpp/){$b[$flag]="3gp";}
	elsif (/video\/quicktime/){$b[$flag]="mov";}
	if (/Content-/ || /NextPart/ || /-+/ || 
	    /^-+[a-zA-Z0-9]+/ || /name=/ || /filename=/ || /^\s+/){}
#"

        else{
	    $file[$flag] .= $_;
	}
    }
}    
#print $#file . ", uid:" . $uid . ",pn:" .$pn . "\n";    
if ($uid>0 && $pn){
    $uplpath=$uplpath . "/" . $uid;
    if (! -d $uplpath) { 
	mkpath [$uplpath] or die $!;
	chmod(0777,$uplpath);
    }
    for ($i=1;$i<=$#file;$i++){
#	print "N;";
	if ($b[$i] =~ /txt/){
	    $text=$file[$i];
	    Jcode::convert($text,'utf8');
	}
	else{
	    $decoded=decode_base64($file[$i]);
	    open (OUTFILE,">" . $uplpath . "/" . $fn . "_" . $i . "." . $b[$i]);
	    binmode(OUTFILE);
	    print(OUTFILE $decoded);
	    close(OUTFILE);
	    chmod(0666,$uplpath . "/" . $fn . "_" . $i . "." . $b[$i]);
	    $sql="insert into upfiles(fname,mobuid,pn,update,descri) values('" . 
		$fn . "_" . $i . "." . $b[$i] . "'," . $uid . ",'" . 
		$pn . "',current_timestamp,'" . $text . "');";
	    $conn->exec($sql);
	}
    }
}



close(FH);
    
exit 0;

