#!/usr/bin/perl

# GiantDisc booklet/cover image utility script
#
# Autor: Rolf Brugger
# Date:  Apr 2004
#



use Getopt::Std;
use lib '/home/music/bin';
use gdgentools;
use DBI;


if (   !getopts ('h:i:sc:m:a:1:2:') # ":" means mandatory parameter
    || !(defined $opt_h)
    || !(defined $opt_a)
    ){ 
  print <<EOF;

Usage: 
  gdbooklet.pl [options] 

GiantDisc booklet/cover image utility script
It can either scan a booklet page or import (check-in) an existing image.

Mandatory options:
  -h dbhost      database host
  -a id          albumid (cddb-id)


optional:
  -s             scan image 
                 The scanning parameters (area, resolution etc) are read 
                 from the database. Therefore, booklet scanning can only 
                 be done, when a 

  -i id          player id (server script instance). This parameter is only
                 required if booklets are scanned.

  -c file        check-in existing image
  
  -m mode        mode: 
                   1u : one booklet page upright
                   1du: one double booklet page upright
                   2u : two booklet pages upright
                   1r : one booklet page right oriented (landscape)
                   1dr: one double booklet page right oriented (landscape)
                   2r : two booklet pages right oriented (landscape)
                 if mode is not specified, 1u is assumed.
                   
  -1 num         first image page number (cover page has number=0)
  -2 num         second image page number (only useful if mode is 2u or 2r)
  
                 if -1 is not specified, then the image is appended
                 to the existing image series of the specified album
                   
  
Example:
  gdbooklet.pl -h 192.168.1.1 -i 3 -s -M 1r -a 0x5f23a3c7 -1 0
  gdbooklet.pl -h 192.168.1.1 -c img.jpg -m 2r -a 0x5f23a3c7 -1 4 -2 5
  
EOF
  exit 0;
}



### init stuff
my $base = "/home/music";

### open DB connection
my $dbh = DBI->connect("DBI:mysql:GiantDisc:".$opt_h, "music", "")
    or die "unable to connect to GiantDisc db";

my $imagemode = "1u";
if (defined($opt_m)){
  $imagemode = $opt_m
}
my $albumid = $opt_a;
my $targetdir=gdgentools::get_ripdirectory(10);  # first directory with at least 10 MB free space
my $tmpimage = "$base/tmp/tmpbooklet.pnm";

# scanmode is one of these: 1u: 1 page upright, 2u: 2 pages upright, 1r: 1 page right (landscape), 2r: 2 pages right (landscape)
# if pagenum is -1, then the image is added to the already existing images for the album
my $twoimages = 0;
if ($imagemode =~ m/2.*/ ){
  $twoimages = 1;
}
my $doublepage = 0;
if ($imagemode =~ m/.d.*/ ){
  $doublepage = 1;
print "doublepage = 1\n";
}

### calculate target filename(s)
my($img1num, $img2num);
if (!defined($opt_1)){ # page1 not defined means "append"
  my $lastfile = `ls $base/??/img0x$albumid-??.jpg | sort | tail -1`;
  chop($lastfile);
  if ($lastfile =~ m/.*-(\d\d).jpg/ ){ # extract last img number for this albumid
    $img1num = sprintf("%02d", $1 + 1);
    $img2num = sprintf("%02d", $1 + 2);
  }
  else{ # no existing img's for this albumid -> start from zero
    $img1num = "00";
    $img2num = "01";
  }
}
else{
  $img1num = sprintf("%02d", $opt_1);
  if (defined($opt_2)){
    $img2num = sprintf("%02d", $opt_2);
  }
  else{
    $img2num = sprintf("%02d", $opt_1+1);
  }
}
my $img1fname = $base."/".$targetdir."/img0x".$albumid."-".$img1num.".jpg";
my $img2fname = $base."/".$targetdir."/img0x".$albumid."-".$img2num.".jpg";



if (defined($opt_s)){ ### Scan an image
  my $playerid = $opt_i;
  ### calulate scan area
  my $scanres = gdgentools::param_value($dbh, $playerid, "scanres");
  my $scancmd = gdgentools::param_value($dbh, $playerid, "scancmd");
  
  my $scanx = gdgentools::param_value($dbh, $playerid, "scanimgx");
  my $scany = gdgentools::param_value($dbh, $playerid, "scanimgy");
  my $scanw = gdgentools::param_value($dbh, $playerid, "scanimgw");
  my $scanh = gdgentools::param_value($dbh, $playerid, "scanimgh");
  my $scanhgt = $scanh;
  my $scanh_pix;
  if ($twoimages || $doublepage){
    $scanhgt = $scanh*2;
    use integer;
    $scanh_pix = ($scanh * $scanres * 10) / 254;
  }

  ### scan the specified area
  print  "$scancmd --resolution $scanres --format=pnm -l $scanx -t $scany -x $scanw -y $scanhgt > $tmpimage \n";
  system "$scancmd --resolution $scanres --format=pnm -l $scanx -t $scany -x $scanw -y $scanhgt > $tmpimage ";

  ### rotate and split if necessary and store to the target path/filename
  my $rotate = "";
  if (($imagemode eq "1r")  || ($imagemode eq "2r") || ($imagemode eq "1dr")){ # rotate
    $rotate = " | pnmflip -rotate90 ";
  }
  if (($imagemode eq "1t")){ # rotate
    $rotate = " | pnmflip -rotate180 ";
  }

  if ($twoimages){
    ### split image in the middle
    print  "pnmcut -bottom $scanh_pix $tmpimage $rotate | pnmtojpeg > $img1fname \n";
    system "pnmcut -bottom $scanh_pix $tmpimage $rotate | pnmtojpeg > $img1fname ";
    print  "pnmcut -top    $scanh_pix $tmpimage $rotate | pnmtojpeg > $img2fname \n";
    system "pnmcut -top    $scanh_pix $tmpimage $rotate | pnmtojpeg > $img2fname ";
  }
  else{
    print  "cat $tmpimage $rotate | pnmtojpeg > $img1fname \n";
    system "cat $tmpimage $rotate | pnmtojpeg > $img1fname ";
  }

  if (($img1num == 0) || ($img2num == 0)){
    ### cover scanned -> store this information in database
    print   ("UPDATE album "
            ."SET coverimg ='img0x".$albumid."-".$img1num.".jpg', "
            .    "modified =CURDATE() "
            ."WHERE cddbid = '$albumid'\n");
    $dbh->do("UPDATE album "
            ."SET coverimg ='img0x".$albumid."-".$img1num.".jpg', "
            .    "modified =CURDATE() "
            ."WHERE cddbid = '$albumid'");
  }

}
else{
  print "currently, image check-in is not implemented\n";
}
#
