#!/usr/bin/env perl

$XBMC = 'http://Xbmc:XbmcXbmc@192.168.16.65';

use LWP::UserAgent;
use HTTP::Request::Common;
use Getopt::Long;
$version = $0." v0.1";
GetOptions("h","x=s","u=s");

if($opt_h) {
    print <<EOM;
$version (c) 2010 th\@bogus.net

WHAT: Sends a YouTube link to your web-server enabled XBMC instance, letting
      you watch the video on the big screen.

usage: $0 [-h] [-x XBMC url] -u <media url>
 -h : this
 -x : xmbc url, default: $XBMC
 -u : media url, e.g. http://www.youtube.com/watch?v=xLu0Ak9Blog 
EOM
    exit(0);
}

if($opt_x) {
    if($opt_x !~ /^https?:\/\/\S+/i) {
        die "STOP: unrecognised xbmc url\n";
    }
    $XBMC=$opt_x;
}

if(!$opt_u) {
    die "STOP: no youtube url provided\n";
} else {
    my $VIDEOID;
    if($opt_u =~ /^https?:.+(\?|\#!)v=([a-z0-9\-_]+)/i) {
        $VIDEOID=$2;
    } elsif($opt_u =~ /^https?:.+v\/([a-z0-9\-_]+)/i) {
        $VIDEOID=$1;
    } else {
        die "STOP: could not recognise youtube video id in url, bug?\n"
    }
    my $ua = LWP::UserAgent->new;
    my $res = $ua->request(POST $XBMC.'/jsonrpc', Content => '{"jsonrpc": "2.0", "method": "XBMC.Play", "params":{ "file" : "plugin://plugin.video.youtube/?action=play_video&videoid='.$VIDEOID.'" }, "id" : 1}"');
    if($res->is_success) {
        exit(0);
    } else {
        print $res->as_string;
    }
    
}


