#!/usr/bin/perl

# Sreview, a web-based video review and transcoding system
# Copyright (c) 2016-2017, Wouter Verhelst <w@uter.be>
#
# Sreview is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.

use strict;
use warnings;

use DBI;

our $config;
require './config.pl';

my $dbh = DBI->connect($config->{dbistring}, '', '') or die "Cannot connect to database!";

my $talkid = $ARGV[0];

$dbh->prepare("UPDATE talks SET progress='running' WHERE id=? AND state='uploading'")->execute($talkid);

$dbh->begin_work;

my $talkslug = $dbh->prepare("SELECT eventid, event, room, starttime::date AS startdate, slug FROM talk_list WHERE id = ?");

$talkslug->execute($talkid);

my $row = $talkslug->fetchrow_hashref();

my $outdirsub = $config->{outputdir};
my $outputdir = &$outdirsub($row->{event}, $row->{room}, $row->{startdate});

my $room = $row->{room};
$room =~ s/^(\S+).*/$1/;
my $slug = $row->{slug};

sub fail() {
	$dbh->prepare("UPDATE talks SET progress='waiting' WHERE id = ? AND state='uploading'")->execute($talkid);
	$dbh->commit;
	die;
}

#foreach my $suffix('.mp4', '-post.mp4', '-post.png', '-pre.mp4', '-pre.png') {
#	my $building = substr($room, 0, 1);
#	unlink(join('/', ($config->{pubdir}, $row->{eventid}, $building, $row->{slug} . $suffix)));
#}
system("rsync -zavHP 'videoteam\@dc17-preview.video.debconf.org:$outputdir/$slug.vp8.webm' /home/sreview/output/dc17/");
system("rsync -zavHP /home/sreview/output/dc17/$slug.vp8.webm veyepar\@apu.debconf.org:/srv/video/video.debian.net/2017/debconf17/");

my $update = $dbh->prepare("UPDATE talks SET progress='done' WHERE id = ? AND state = 'uploading'");
$update->execute($talkid);

$dbh->commit;
