#! /usr/bin/perl

# Copyright © 2014 Jonas Smedegaard <dr@jones.dk>
# Description: Extract copyright/licensing metadata from binary files
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use warnings;
use IPC::System::Simple;
use autodie qw(:all);
use feature 'say';
use Regexp::Assemble;
use Image::ExifTool qw(:Public);

BEGIN { $Image::ExifTool::configFile = '' }

my $exifTool = new Image::ExifTool;

my $dispatch = {
	'.*\.(png|jpg|jpeg|gif|icc)' => sub {
		my ( $infile, $outfile ) = @_;
		my $info = $exifTool->ImageInfo($infile, '*Name*', '*Copyright*');
		open(my $fh, ">>", $outfile);
		foreach (sort keys %$info) {
#			print $fh "$_: $$info{$_}\n";
			my $tagdesc = $exifTool->GetDescription($_);
			print $fh "$tagdesc: $$info{$_}\n";
		}
	},
	'.*\.(ttf|otf)' => sub {
		my ( $infile, $outfile ) = @_;
		system 'sh', '-c',
			"otfinfo -i '$infile' | egrep 'Copyright|Licens' > '$outfile'";
	},
};

my $re = Regexp::Assemble->new( track => 1 )->add( keys %$dispatch );

while( <> ) {
	chomp;
	if( $re->match($_) ) {
		my $infile = $re->mvar(0);
		my $outfile = "$infile.metadata_dump";
		if ( -e $outfile ) {
			say STDERR "ERROR: dumpfile exist: $outfile";
			say STDERR "       remove or put aside and try again";
			exit 1;
		}
		$dispatch->{ $re->matched }( $infile, $outfile );
	}
	else {
		last if /q/;
		print "\tignored\n";
	}
}
