#!/usr/bin/env perl
use 5.014;
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use JSON::PP ();
use Image::Privacy::ByteSanitizer;

our $VERSION = '1.00';

my ($opt_json, $opt_out, $opt_strip_icc, $opt_help, $opt_ver);
GetOptions(
    'json'       => \$opt_json,
    'out|o=s'    => \$opt_out,
    'strip-icc'  => \$opt_strip_icc,
    'help|h'     => \$opt_help,
    'version|v'  => \$opt_ver,
) or die "Usage: image-privacy-sanitize [--json] [--strip-icc] [--out CLEAN.jpg] <image>\n";

if ($opt_ver) {
    print "image-privacy-sanitize v$VERSION (Image::Privacy::ByteSanitizer)\n";
    exit 0;
}

if ($opt_help || !@ARGV) {
    print <<"USAGE";
Usage: image-privacy-sanitize [OPTIONS] <file.jpg | file.png | file.webp>

Options:
  --json           Output metadata leak inspection report as JSON
  --out, -o <f>    Write losslessly sanitized image container to <f>
  --strip-icc      Also strip embedded ICC color profiles (default: preserve)
  --version, -v    Print version
  --help, -h       Show this help message
USAGE
    exit($opt_help ? 0 : 1);
}

my $input = shift @ARGV;
open my $fh, '<:raw', $input or die "Cannot read '$input': $!\n";
local $/;
my $bytes = <$fh>;
close $fh;

my $san = Image::Privacy::ByteSanitizer->new(preserve_icc => $opt_strip_icc ? 0 : 1);

if (defined $opt_out) {
    my $clean = $san->sanitize_bytes($bytes);
    open my $ofh, '>:raw', $opt_out or die "Cannot write '$opt_out': $!\n";
    print {$ofh} $clean;
    close $ofh;
    printf "Sanitized %s (%d -> %d bytes, 0%% pixel recompression) -> %s\n",
        $san->detect_format($bytes), length($bytes), length($clean), $opt_out;
    exit 0;
}

my $rep = $san->inspect_bytes($bytes);
if ($opt_json) {
    print JSON::PP->new->utf8->canonical->pretty->encode($rep);
    exit 0;
}

printf "Format: %s (%d bytes) | Clean: %s\n",
    $rep->{format}, $rep->{size_bytes}, ($rep->{privacy_clean} ? 'YES' : 'NO');
if (@{ $rep->{privacy_leaks} }) {
    printf "Leaks:  %s\n", join(', ', @{ $rep->{privacy_leaks} });
}

exit 0;

__END__

=head1 NAME

image-privacy-sanitize - Lossless binary EXIF, GPS, XMP, and IPTC sanitizer for JPEG, PNG, and WebP

=head1 SYNOPSIS

    image-privacy-sanitize photo.jpg
    image-privacy-sanitize --out clean.jpg photo.jpg

=head1 AUTHOR

Islam Ayoub (UTILVO) E<lt>info@utilvo.comE<gt>

=cut
