#!/usr/bin/perl

use RPC::XML::Server;

use lib '/opt/oma/reboot';
use REBOOTPARSE;
use REBOOT;
use lib '/opt/oma/oma-bin';
use OMA;
use lib '/opt/oma/transact';
use XSQL;
use Encode;
use XML::RSS;
use HTTP::Date;
use URI;

local %sqlattr;
local %sqlval;
local $sqlcmd;
local %count;

$db = OMA::opendb;

sub parsetag {
	local $xmltext = shift;
	local $op = shift;	
	local $id = shift;
	local $filename = shift;

	$cn1 = $cn2 = $cn3 = 0;
	local @xmlarr = split(/\n/,$xmltext);
	$xmltext = join("\n",@xmlarr);

	local $p = XML::Parser->new(Style => 'Stream', ProtocolEncoding => 'UTF-8');
	local $doc = $p->parse($xmltext);

	local $tmp;
	local @counter;

	undef(@counter);
	undef(%count);

	local $ctype;
	local $cattr;
	local $ctag;
	local $identifierg;

	$importer = $id;

	sub StartDocument { $title="";}
	sub EndTag {
		local $exp = shift;
		local $type = shift;
		local %attr = %_;
		local $tag = $_;

		$ctype = $cattr = $ctag = "";
	}

	sub Text {
		local $exp = shift;
		local $type = shift;
		local %attr = %_;
		local $tag = $_;

		local $sqlfield = $ctype;
		$sqlfield =~ s/:/__/g;
		if($sqlfield && $tag) {
			$tag =~ s/'/\\'/g;
			if($sqlfield eq "dc__contributor") {
				$cn1 = 0 if(!defined($cn1));

				if($cattr) {
					$sqlattr{"reboot_contributor$cn1"}[$count{"reboot_contributora$cn1"}] = $sqlfield ."__role";
					$sqlval{"reboot_contributor$cn1"}[$count{"reboot_contributor$cn1"}++]="'$cattr'";
					if($cattr eq "Importer") {
						$importer = $tag;
					}
				}

				$sqlattr{"reboot_contributor$cn1"}[$count{"reboot_contributor$cn1"}]=$sqlfield;
				$sqlval{"reboot_contributor$cn1"}[$count{"reboot_contributor$cn1"}++]="'$tag'";
				$cn1++;

			} elsif($sqlfield eq "dc__creator") {
				$cn2 = 0 if(!defined($cn2));

				if($cattr) {
					$sqlattr{"reboot_creator$cn2"}[$count{"reboot_creator$cn2"}]=$sqlfield ."__role";
					$sqlval{"reboot_creator$cn2"}[$count{"reboot_creator$cn2"}++]="'$cattr'";
				}

				$sqlattr{"reboot_creator$cn2"}[$count{"reboot_creator$cn2"}]=$sqlfield;
				$sqlval{"reboot_creator$cn2"}[$count{"reboot_creator$cn2"}++]="'$tag'";
				$cn2++;

			} elsif($sqlfield =~ /^dc__relation/) {
				$cn3 = 0 if(!defined($cn3));

				if($cattr) {
					$sqlattr{"reboot_relation$cn3"}[$count{"reboot_relation$cn3"}]=$sqlfield ."__role";
					$sqlval{"reboot_relation$cn3"}[$count{"reboot_relation$cn3"}++]="'$cattr'";
				}

				$sqlattr{"reboot_relation$cn3"}[$count{"reboot_relation$cn3"}]=$sqlfield;
				$sqlval{"reboot_relation$cn3"}[$count{"reboot_relation$cn3"}++]="'$tag'";
				$cn3++;

			} elsif($sqlfield =~ /^dc__/) {

				$sqlattr{'reboot_page'}[$count{'reboot_page'}]=$sqlfield;

				if($sqlfield eq "dc__date__issued") { $newid = str2time($tag);  }
				if($sqlfield eq "dc__title") { $title = $tag if(!$title); }
				if($sqlfield eq "dc__title__alternative") { $title = $tag if(!$title); }
				

				if($sqlfield =~ /^dc__format__extent/) {
					$sqlval{'reboot_page'}[$count{'reboot_page'}++]="$tag";
				} elsif($sqlfield eq "dc__identifier") {
					$identifier = $tag;
					$sqlval{'reboot_page'}[$count{'reboot_page'}++]="'$tag'";
				} elsif($sqlfield eq "dc__date__issued") {
					$sqlval{'reboot_page'}[$count{'reboot_page'}++]=$newid;
				} elsif($sqlfield eq "dc__date__digitized") {
					$sqlval{'reboot_page'}[$count{'reboot_page'}++]=$tag;
				} elsif($sqlfield eq "dc__date__created") {
					$sqlval{'reboot_page'}[$count{'reboot_page'}++]=$tag;
				} else {
					$sqlval{'reboot_page'}[$count{'reboot_page'}++]="'$tag'";
				}

			}
		}
	}

	sub StartTag {
		local $exp = shift;
		local $type = shift;
		local %attr = %_;
		local $tag = $_;
		local $otag = $tag;

		chop($otag);

		$ctype = $type;
		$cattr = $attr{'role'};
		$ctag = $tag;

	}

	my ($y,$m,$d) = split(/-/,(split(/\ /,HTTP::Date::time2isoz($newid)))[0]);
	$branch = "/time/$y/$m/$d";
	$sqlcmd ="";
	foreach $k (keys %sqlattr) {
		$tmp = $sqlattr{$k};
		@counter = @$tmp;

		if($op eq "insert") {
print "1.\n";
#			$newid = time;
			if($k eq "reboot_page") {
				$sqlcmd .= "\nINSERT INTO $k ( ID, location, username, expire, path,  ";
			} elsif ($k =~ /^reboot_contributor/ ||
					 $k =~ /^reboot_creator/ ||
                     $k =~ /^reboot_relation/) {
				my $nk = $k; chop($nk);
				$sqlcmd .= "\nINSERT INTO $nk ( ID, location, ";
			} else {
				$sqlcmd .= "\nINSERT INTO $k ( ID, location, ";
			}
print "2.\n";
			for($i=0;$i<=$#counter;$i++) {
				 $sqlcmd .= "$sqlattr{$k}[$i],";
			}
			$sqlcmd =~ s/,$/\)/;
			$sqlcmd .= "\nVALUES ( ";
print "3.\n";
			if($k eq "reboot_page") {
				$sqlcmd .= "$newid,'100tage.reboot.fm','$importer',0,'/REBOOT-RECORDINGS/',";
			} else {
				$sqlcmd .= "$newid,'100tage.reboot.fm',";
			}
			for($i=0;$i<=$#counter;$i++) {
				$sqlcmd .= "$sqlval{$k}[$i],";
			}
print "4.\n";
			$sqlcmd =~ s/,$/\);\n/;
			if($k eq "reboot_page") {
				if(!-d "/data/archive/REBOOT-RECORDINGS/$newid") {
					do {
						$newsid = OMA::nextsid("item_sid");
					} while($newsid < 10);
					$node = OMA::getnode($branch);
					if(!$node) {
						OMA::makebranch($branch);
						$node = OMA::getnode($branch);
					}
print "5.\n";
					$sqlcmd .= "\nINSERT INTO item VALUES ($newsid, $node, '$title', 'reboot', 0, 1);\n\n";
					$sqlcmd .= "INSERT INTO reboot_conn VALUES ($newsid,$newid,'100tage.reboot.fm',0,$newsid);\n\n";
print "6.\n";
					print "mkdir /data/archive/REBOOT-RECORDINGS/$newid\n";
					mkdir("/data/archive/REBOOT-RECORDINGS/$newid",0775) or die "Can't create desired directory";
					$fileupdateonly=0;
				}
				else {
					$fileupdateonly=1;
				}
print "7.\n";
				system("cp /data/recording/shows2archive/$filename /data/archive/REBOOT-RECORDINGS/$newid/");
print "n.\n";
			}
		}
	}
	undef(@counter);
	undef(%count);
	undef(%sqlattr);
	undef(%sqlval);
print "hmm...\n";
	$sqlcmd .= "INSERT INTO reboot_contributor VALUES ($newid,'100tage.reboot.fm','','');\n";
	$sqlcmd .= "INSERT INTO reboot_creator VALUES ($newid,'100tage.reboot.fm','','');\n";
print "shit...\n";
	if($fileupdateonly == 1) {
		return("");
	}
	return(Encode::encode("utf8",$sqlcmd));
}

sub receive_dc_set {
	local $serv = shift;
	local $dc_set = shift;
	local $username = shift;
	local $filename = shift;
	local $id = shift;

	if(-f "/data/archive/REBOOT-RECORDINGS/$id/$id.ogg") {
		print "OK, APPEND!\n";
		system("cat /data/recording/shows2archive/$filename >> /data/archive/REBOOT-RECORDINGS/$id/$id.ogg");
	} else {
		print "OK, NEW ENTRY\n";
		local $sqlcmd = parsetag($dc_set,"insert",$username,$filename);
		$sqlcmd =~ s/dc__description__tableOfContent/dc__description__toc/;
		print "\ncmd: $sqlcmd\n";
		$st=$db->prepare($sqlcmd);
		$st->execute();
	}
	return("ok.");
}

$srv = new RPC::XML::Server->new(host => '0.0.0.0', port => 9501) || die("cant start server");
$srv->compress_thresh(10000000);


$srv->add_method({	name => 'oma.receive_dc_set',
		signature => [ 'string string string string int' ],
		code => sub { return(receive_dc_set($_[0],$_[1],$_[2],$_[3],$_[4])); }
		}
);

$srv->server_loop; # Stays in an accept/connect loop



