#!/usr/bin/perl

use GD::Barcode::EAN13;
use GD::Barcode::Code39;
use POSIX qw( ceil );

my $barcode = shift || "";
my $line1 = shift || "";
my $line2 = shift || "";

#$barcode = 12345678123456;
#$line1 = "Coca Cola";
#$line2 = "12.30€";

if ($line2) {
  $line2=~ s/\s\-\s.*?$//;
  $line2 = sprintf("%.2f", $line2);
  $line2="$line2€";
}

my $type = 'EAN13';

if (length($barcode) < 12 || length($barcode) > 13) {
  $type = 'Code39';
}

if (! $barcode) {
  die "Usage: $0 <type> <barcode>\n";
}

my $file = "/tmp/barcode_$$.png";

if ($type eq 'EAN13') {
  open(F, "> $file");
  binmode(F);
  print F GD::Barcode::EAN13->new($barcode)->plot(Height => 60)->png;
  close(F);
  process_image($file, $line1, $line2);

}
elsif ($type eq 'Code39') {
  open(F, "> $file");
  binmode(F);
  print F GD::Barcode::Code39->new('*'.$barcode.'*')->plot(Height => 60)->png;
  close(F);
  process_image($file, $line1, $line2);
}
else {
  die "Invalid type...\n";
}

print $file."\n";

sub process_image {
  my $file = shift;
  my( $line1, $line2 ) = @_;

  my $lines_str = "";
  $lines_str = $line1."\n" if $line1;
  $lines_str = $lines_str. $line2 if $line2;

  system("convert \"$file\" -gravity south -extent 200x100 -background white \"".$file."_1\"");

  if ($lines_str) {
    system("convert \"".$file."_1\" -gravity NorthWest -pointsize 20 -annotate +5+2 '$lines_str' $file");
  }
}

