#!/usr/bin/perl -w

$file = shift @ARGV or exit;
$size = -s $file or exit;

close STDERR unless -t STDOUT;
  
if ($file =~ /\.jpe?g$/i and $size > 2**16 and
    searchpath('djpeg') and searchpath('cjpeg') and
    searchpath('jpegtran') and searchpath('jpegexiforient'))
{
  $qfile = shellquote($file);
  %rot = (6 => 90, 3 => 180, 8 => 270);
  # https://stackoverflow.com/questions/9371273/how-can-i-display-the-orientation-of-a-jpeg-file
  $_ = `identify -format '%[EXIF:Orientation]' $qfile||jpegexiforient $qfile`;
  chomp;
  $rot = $rot{$_}||0;
  $cmd = "djpeg $qfile | cjpeg -optimize";
  $cmd .= " | jpegtran -rotate $rot -trim" if $rot;
  warn "\$ $cmd|\n" if -t STDIN;
  $jpg = `$cmd`;

  if ($jpg and length $jpg > 1024 and length $jpg < $size*0.8) {
    if (open $file,'>',$file) {
      print {$file} $jpg;
      close $file;
    }
  }
}

sub searchpath {
  my $prg = shift;
  my ($path,@PATH);

  foreach my $path (split(':',$ENV{PATH})) {
    return $prg if -x "$path/$prg";
  }
  return '';
}

sub shellquote {
  local $_ = shift;
  s/([^\w\@\/!^%:_.,=+-])/\\$1/g;
  return $_;
}
