#!/usr/bin/perl -w
# CGI slide-show control for dealing with Rendez-vous server.
# (c)2011 Felix Hauri - http://realtime.f-hauri.ch - realtime@f-hauri.ch
# GNU Lesser General Public License
# All this work is published under terms of LGPL V3 http://www.gnu.org/licenses/lgpl.html
# This tool open existing UNIX Socket for sending control commands from
# standard html POST to streamed server push control flow.

use strict;
use CGI qw(:standard form delete_all);
use IO::Socket;
my $q=new CGI;

my $cgipass=`cat ../cgipass`;
chomp $cgipass;
my $reffile='../public_html/slideshow/'.$1.'.svg' if
    $q->param('name') && $q->param('name') =~ /^([a-zA-Z0-9_.-]*)$/;
my @titles;
if ($reffile && -f $reffile) {
    open my $fh,"<".$reffile;
    my ($szIsFrame,$szTitle,$szSeqNum);
    while (<$fh>) {
	$szTitle=$1 if /:title="(.*)"/;
	$szIsFrame=1 if /<\S+:frame/;
	$szSeqNum=$1-1 if /:sequence="(\d+)"/;
	($titles[$szSeqNum],$szIsFrame)=($szTitle) if $szIsFrame && /:.*\/>/;
    };
    close $fh;
};

print header(-charset=>'utf-8',-content_type=>'text/plain');
if (defined param("rdzvs") &&  param("rdzvs") =~ /^([a-z0-9]+)$/) {
	my $rdzvs=$1;
	my $sockname="/tmp/cgi-rendezvous-serveur-".$1;
	if (defined param('Show') && param('Show') =~ /^(\d+|Next|Prev)$/) {
		my $cmde=$1;
		my $sk=IO::Socket::UNIX->new($sockname) or die;
		print $sk $cmde;
		close $sk;
	};
        print "titles,".join ",",@titles;
} elsif ((defined param('browse')) && (param('browse') eq $cgipass)) {
   my %rdzvs;
    open my $lsofhndl,"lsof|";
    while (<$lsofhndl>) {
	if (m|nph-follo\s+(\d+)\s.*/tmp/cgi-rendezvous-serveu|) {
	    my $cmdSpid=$1;
	    if (`/bin/sed -zn '/HTTP_REFERER/p' /proc/$cmdSpid/environ` =~
		m|slideshow/(.*)[?]handler=([a-z0-9]+)\b|) {
		$rdzvs{$1.";".$2} = 1;
		print STDERR 'E... '.$1."..".$2."\n";
	    };
	};
    };
    close $lsofhndl;
    my @rdzvs=sort keys %rdzvs;
    map {
        (my $file,my $hand)=split(';');
        printf "http://realtime.f-hauri.ch/slideshow/command.html?name=%s&hand=%s\n", $file, $hand;
        printf "http://realtime.f-hauri.ch/slideshow/%s?handler=%s\n", $file, $hand;
    } @rdzvs if @rdzvs;
};
