#!/usr/bin/perl -w

use strict;
use v5.10;
use IO::Socket::SSL;

my $proto = 'tcp';
my $path = '/services/rest';
my ($key, $id) = do '/home/pegasus/flickr.keys';

sub fail {
	say <<"EOF";
Status: 503
Content-type: text/plain

@_
EOF
	exit;
}

select((select(STDOUT), $| = 1)[0]);
my $serv = 'https';
#my $serv = 'http';
my $host = 'api.flickr.com';
#my $host = 'localhost';
my $socket = IO::Socket::SSL->new(
	PeerAddr => $host,
	PeerPort => scalar getservbyname($serv, $proto),
	Proto    => $proto
) or fail "Can't create socket: $@";
#my $socket = IO::Socket::INET->new("$host:".getservbyname($serv, $proto))
select((select($socket), $| = 1)[0]);

my $query = "method=flickr.people.getPublicPhotos&api_key=$key&user_id=$id";
print $socket "GET $path?$query HTTP/1.1\r\n";
print $socket "Connection: keep-alive\r\n";
print $socket "Host: $host\r\n\r\n";
while ($_ = <$socket>) {
	/<photo\b/ && do {
		$id = (/\bid="([^"]*)"/)[0];
		$query = "method=flickr.photos.getInfo&api_key=$key&photo_id=$id";
		last;
	};
}
do { $_ = <$socket>; } until m!</rsp>!;
my ($server, $farm, $osecret, $oformat);
print $socket "GET $path?$query HTTP/1.1\r\n";
print $socket "Host: $host\r\n\r\n";
while ($_ = <$socket>) {
	/<photo\b/ && do {
		$server = (/\bserver="([^"]*)"/)[0];
		$farm = (/\bfarm="([^"]*)"/)[0];
		$osecret = (/\boriginalsecret="([^"]*)"/)[0];
		$oformat = (/\boriginalformat="([^"]*)"/)[0];
		close $socket;
		last;
	};
}

print<<"EOF";
Content-type: text/html

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Screenshot of the moment...</title>
		<style type="text/css">
* { padding: 0; margin: 0; background: #000; }
html, body { height: 100%; overflow: hidden; }
body { text-align: center; display: table; width: 100%; }
div { display: table-cell; vertical-align: middle; }
img { margin: auto; }
		</style>
	</head>
	<body>
		<div>
			<img src="https://farm$farm.staticflickr.com/$server/${id}_${osecret}_o.$oformat" />
			<script type="text/javascript">
document.images[0].onload = function () {
	var img = document.images[0];
	var imgh = img.height;
	var imgw = img.width;
	var ar = imgw / imgh;
	window.onresize = function () {
		img.style.display = "none";
		var winw = document.body.scrollWidth;
		var winh = document.body.scrollHeight;
		if (ar < winw / winh) {
			img.width = winh * imgw / imgh;
			img.height = winh;
		} else {
			img.width = winw;
			img.height  = winw * imgh / imgw;
		}
		img.style.display = "block";
	}
	window.onresize();
}
			</script>
		</div>
	</body>
</html>
EOF
