#!/usr/bin/perl

use strict;
use warnings;
use 5.014;
use HTTP::Tiny;
use Config::Tiny;
use DBI; # reqires perl-DBD-SQLite, perl-DBI            

my $ytdown = "/tmp/youtubedown.pm";

if (! -f $ytdown || (stat($ytdown))[9] < time-7*24*60*60) { # update youtubedown once a week
	system(qq{curl -sAMozilla https://www.jwz.org/hacks/youtubedown|sed '\$d'|sed '\$c1\\;' > $ytdown});
} #                                                  delete "exit 0;"---^         ^---replace "main();" with "1;"

require $ytdown; # note: can't use 'use', as that parses at compile time (before youtuebdown is downloaded)

sub find_player_url {
	# request a random video (this is the first ever uploaded one, "me at
	# the zoo". it shouldn't go away any time soon) note that the string
	# we're looking for contains our locale, so specify it to avoid it
	# changing.
	my $response = HTTP::Tiny->new
		->get("https://www.youtube-nocookie.com/embed/jNQXAC9IVRw?hl=en&gl=US")
		->{content};

	# extract the src attribute from the script tag whose name attribute
	# has value "player_ias/base":
	if ($response =~ m{(<script .*?\bname=["']player_ias/base["'].*?>)}) {
		if ($1 =~ m{src=["'](.*?)["']}) {
			return $1;
		}
	}
	return undef;  # unable to extract player/base.js URL
}

my $cf = Config::Tiny->read( $ENV{YT_CONFIG} // "/etc/yt/config.ini", 'utf8' );
my $new_url = find_player_url();

my $dbh = DBI->connect("dbi:SQLite:dbname=$cf->{global}->{database}", undef, undef, {
	AutoCommit => 1,
	sqlite_unicode => 1,
	sqlite_open_flags => 1, # read-only
});

my $sth = $dbh->prepare("SELECT url FROM cipher");
$sth->execute();
my ($player_url) = @{$sth->fetchrow_arrayref()};

exit 1 unless $new_url;  # failed
exit 0 if $player_url eq $new_url;  # unchanged

my ($cipher_id) = $player_url =~ m@/s/player/(.*?)\.js@;
my ($sts, $algo) = split / /, guess_cipher($cipher_id, 0, 0), 2;

$dbh->prepare("
	INSERT OR REPLACE INTO cipher (url, sts, algorithm)
	                VALUES (?, ?, ?)
")->execute($new_url, $sts, $algo);
