#!/usr/bin/perl -w

#
# So: flickr-to-postcard.
# Gets a somewhat random flickr image and labels it in a bold way to create
# a one-of-a-kind postcard.
#

my $font = "Stencil.ttf"; #"Stencil-Std-Bold"

my $url = "";
if (@ARGV == 0) {
	my $list = `wget 'http://www.flickr.com/photos/tags' -O- --quiet`;
	$list =~ s/Over the last week.*$//;
	my @recent = ();
	while ($list =~ s/"(\/photos\/tags\/[^"]+)"//) {
		push @recent, $1;
	}
	if (@recent == 0) {
		print $list . "\n";
		print "No recent?\n";
		exit(1);
	}
	$url = 'http://www.flickr.com' . $recent[int(rand(@recent))];
	print $url . "\n";
	$list = `wget '$url' -O- --quiet`;
	@recent = ();
	while ($list =~ s/<span class="photo_container pc_t"><a href="([^"]+)"//) {
		push @recent, $1;
	}
	if (@recent == 0) {
		print $list . "\n";
		print "No photos?\n";
		exit(1);
	}
	$url = 'http://www.flickr.com' . $recent[int(rand(@recent))];
	print $url . "\n";
	#exit 1;
} else {
	$url = $ARGV[0];
}
$url =~ s/(['])/'"'"'/g;
$url =~ s/\/$//;
my $frontpage = `wget '$url' -O- --quiet`;
my @tags = ();
while ($frontpage =~ s/tags_rawA.push\('([^']+)'//) {
	push @tags, $1;
}
if (@tags == 0) {
	print "No tags!\n";
	exit 1;
}
print "Tags:\n  " . join("\n  ", @tags) . "\n";
$url .= "/sizes/o/";
print $url . "\n";
my $page = `wget '$url' -O- --quiet`;
if (!($page =~ m/<a href="([^"]+)">Download the/)) {
	#print $page . "\n";
	print "No 'Download the'... sorry.\n";
	print "  Probably this means the image isn't for saving to disk.\n";
	exit 1;
}
my $src = $1;
print "Source: $src\n";
$src =~ s/(['])/'"'"'/g;
system("wget '$src' -Otemp.jpeg --quiet");

my $info = `identify temp.jpeg`;
if (!($info =~ m/^temp.jpeg JPEG (\d+)x(\d+) /)) {
	print "Image not jpeg...\n";
	exit 1;
}
my ($x, $y) = ($1, $2);
my $m = 1;
my $tag = $tags[int(rand(@tags))];
print length($tag) . "\n";
if (int(rand(2))) { $m = -1; }
my $cmd = 'rotate ' . $m * int(4 + rand(10)) . ' font ' . $font . ' font-size ' . int($x * 1.6 / length($tag)) . ' fill yellow stroke white stroke-width 5 text 0,0 \"' . $tag . '\"';
print $cmd . "\n";
system('convert temp.jpeg -gravity South -draw "' . $cmd . '" postcard.jpeg');

