#! /usr/bin/perl

use lib qw(.);
use DBI;
use POSIX;
use Sesse::pr0n::Common;
use strict;
use warnings;

use Sesse::pr0n::Config;
eval {
	require Sesse::pr0n::Config_local;
};

my $dbh = DBI->connect("dbi:Pg:dbname=pr0n;host=" . $Sesse::pr0n::Config::db_host,
	$Sesse::pr0n::Config::db_username, $Sesse::pr0n::Config::db_password)
	or die "Couldn't connect to PostgreSQL database: " . DBI->errstr;
$dbh->{RaiseError} = 1;

# TODO: Do we need to care about renders?
for my $id (@ARGV) {
	my $dir = POSIX::floor($id / 256);
	my $base = $Sesse::pr0n::Config::image_base . "cache/$dir";
	my @res = ();
	for my $file (<$base/$id-*-nobox.jpg>) {   # TODO: --1--1.jpg, too.
		my $fname = File::Basename::basename($file);
		my ($width, $height) = $fname =~ /^$id-(\d+)-(\d+)-nobox\.jpg$/ or die $fname;
		(my $avif_file = $file) =~ s/jpg$/avif/;
		unless (-r $avif_file) {
			push @res, ($width, $height);
			print "$id to $width x $height...\n";
		}
	}
	if (scalar @res > 0) {
		my $filename = Sesse::pr0n::Common::get_disk_location({}, $id);

		# Look up the width/height in the database.
		my ($dbwidth, $dbheight);
		my $ref = $dbh->selectrow_hashref('SELECT width,height FROM images WHERE id=?', undef, $id);
		$dbwidth = $ref->{'width'};
		$dbheight = $ref->{'height'};

		Sesse::pr0n::Common::make_cache({}, $filename, $id, $dbwidth, $dbheight, 'avif', @res);
	}	
}
