#!/usr/bin/perl -w


#<head><title>mimemail2iets anders</title>
#</head>


use strict;
$|++;


use MIME::Parser;
use MIME::Head;
use Date::Manip;
use Data::Dumper;

# MIME::Tools->debugging(1);

#date
my $now=ParseDate('now');
my $date=UnixDate($now,"%Y%m%d-%H%M");

#output
my $output_dir="/home/snap/incoming";

#save
my $savedir="/home/snap/gfx";

### Create parser, and set some parsing options:
my $parser = new MIME::Parser;


$parser->output_under("/ttmp/tt/snapcam/mimemail");


### Alter its filer:
my $filer = MIME::Parser::FileInto->new($output_dir);
$filer->ignore_filename(1); 
$filer->output_prefix("$date");
$parser->filer($filer);

### Parse input:
my $entity = $parser->parse(\*STDIN) or die "parse failed\n";


# get subject
my $head    = $entity->head();
my $subject = $head->get('Subject');


$subject =~ s!\s*$!!;
$subject =~ s!\s!_!gics;
$subject =~ s!\W!!gics;
$subject =~ s!_*$!!;


print "subject:[$subject]\n";



### Take a look at the top-level entity (and any parts it has):
# $entity->dump_skeleton;


# files
my @files=`cd $output_dir && ls -1 *`;
chop @files;

my $comment;
my $commentfile;

foreach my $file(@files){
  print " [$file] ";
  
  my $savefile =  $file;
  $savefile =~ s!\.jpg$!\.$subject\.jpg!;
  print " $savefile \n";
  if ($file =~ m!jpg$!){
    print `cp "$output_dir/$file" "$savedir/$savefile" || echo failed cp`;
    `chmod a+rw "$savedir/$savefile"`;
    $commentfile="$savedir/$savefile" unless $commentfile;
  }
  if ($file =~ m!txt$!){
    $comment .= `cat $output_dir/$file`;
  }
}

$comment =~ s!\n+$! !gcs;
$comment =~ s!\s+! !gcs;
$comment =~ s!\s+$!!gcs;
$comment =~ s!^\s+!!gcs;



if ($comment && $commentfile){
  
  #my $file=$commentfile;
  #my $savefile =  $file;
  #$savefile =~ s!\.jpg$!\.$subject\.jpg!;
  print " $commentfile [$comment] \n";
  
  print "/usr/local/bin/wrjpgcom -comment \"$comment\" \"$commentfile\" >  \"$commentfile.tmp\"";
  
  
  
  print `(/usr/local/bin/wrjpgcom -comment "$comment" "$commentfile" > "$commentfile.tmp" && mv "$commentfile.tmp" "$commentfile") || echo failed wrjpgcom $commentfile`;
  
  `chmod a+rw $commentfile`;
}


  

#purge
$parser->filer->purge;


#print Dumper($parser);

my $ecomment=$comment;
$ecomment =~ s!\s+!+!;

print `cd $savedir && ~jip/bin/thumb.pl`;
`~jip/bin/bord`;

