#!/usr/bin/perl

use strict;
use DBI;
use Digest::MD5 qw/md5_hex/;
use CGI;

my $cgi = new CGI;

my %cfg = do 'config.pl';

my $file;
my $asset_path = $cfg{'asset_path'};
my $noimg = $cfg{'noimg'};

my $dbh = DBI->connect("dbi:mysql:$cfg{'dbdb'}:$cfg{'dbhost'}",$cfg{'dbuser'},$cfg{'dbpass'});


my $go;

$go = 1;

my $celebid = $cgi->param('cid');
my $key = $cgi->param('k');
my $f = 1;

# Verify the hash key matches, otherwise tell them to get bent.
if ($key ne genkey()) {
	$go = 0;
}


if (!$celebid || !$go) {
	$file = $noimg;
} else {
	if (!$f) {
		my $q = "SELECT asset from assets where assetowner=\"$celebid\" AND ownerclass='c' AND assetclass=\"headshot\";";
		my $sth = $dbh->prepare($q);
		$sth->execute();
		my $asset = $sth->fetchrow_array();
		if (!$asset) {
			$file = $noimg;
		} else {
			my $imgpath = $asset_path . "/" . $asset;
			if (-e $imgpath) {
				$file = $imgpath;
			} else {
				$file = $noimg;
			}
		}
	} else {
		my $imgpath = $asset_path . "/c$celebid-headshot.jpg";
		if (-e $imgpath) {
			$file = $imgpath;
		} else {
			$file = $noimg;
		}
	}
}
#$dbh->disconnect;

#
# Sub-req to image file
#

print "Content-type: image/jpeg\n\n";
open (FIL, $file);
while (<FIL>) {
	print $_;
}
close (FIL);


sub genkey() {
	my $extra = shift;
	my @lt = localtime;
	my $year = $lt[5] + 1900;
	my $month = $lt[4] + 1;
	my $day = $lt[3];

	my $g = md5_hex("$year$month$day" . ($extra ? $extra : ""));
	return $g;
}
