#!/usr/bin/perl

use Getopt::Long;
use Term::ANSIColor;

############################################################################
#   This is pdfmerge4unix version 1.0.6
#
#   pdfmerge4unix is a command line utility program that merges pdf
#   files in unix-based platforms.
#
#   Copyright (C) 2003 Didier F.B Casse
#   Copyright (C) 2010-2015 Dominic Hopf <dmaphy@googlemail.com>
#   Copyright (C) 2014 Michael Spahn <michael@spahn.me>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
############################################################################

GetOptions('help', 'h', 'force', 'f');

$usage = <<"END_OF_USAGE";
This is pdfmerge4unix version 1.0.4. pdfmerge4unix is a command line utility
program that merges pdf files in unix-based platforms

Syntax:  pdfmerge file1.pdf file2.pdf... fileN.pdf outfile.pdf
         All files to concatenate must either be in the current directory or
         in a subdirectory of the current directory.

Options:
            --help                  displays this brief help; same as -h
            --force                 overwrite existing file; same as -f

URL:       http://dmaphy.github.com/pdfmerge/
END_OF_USAGE


if ($opt_help or $opt_h)
{
	print $usage;
	exit 0;
}


$mergedfile = pop(@ARGV);

foreach $ARGV (@ARGV) {
	if ($ARGV !~ /\/$mergedfile$/) {
		$i++;
	}
}

if ($i < 2)
{
	# Wrong parameters or only one PDF defined
	print $usage;
	exit 0;
}


if (!$opt_force and !$opt_f and -e $mergedfile) {
    print color("red"), "$mergedfile should not exist, it's the name of your output file!\n", color("reset");
    exit 1;
}


my $filecontent = << "END_OF_INCANTATION";
%!PS
/_begin_job_
{
        /tweak_save save def
        /tweak_dc countdictstack def
        /tweak_oc count 1 sub def
        userdict begin
}bind def

/_end_job_
{
        count tweak_oc sub{pop}repeat
        countdictstack tweak_dc sub{end}repeat
        tweak_save restore
}bind def

END_OF_INCANTATION


foreach $ARGV (@ARGV) {
    if (! -e $ARGV) {
        print color("red"), "Input file $ARGV does not exist\n", color("reset");
        exit 1;
    } elsif ($ARGV =~ /\/$mergedfile$/) {
		# Skip this file if is destination file.
		#
		# For example using:
		#    pdfmerge *.pdf target.pdf --force
        next;
    }

	# Determine if this is an absolute or relative path
	if ($ARGV =~ /^\//) {
		$prefix = '';
	} else {
		$prefix = './';
	}

	$filepath = $prefix . $ARGV;

    $filecontent .= "\n_begin_job_\n";
    $filecontent .= "($filepath)runlibfile\n";
    $filecontent .= "_end_job_\n";
}

`echo "$filecontent" | ps2pdf -dNOSAFER -P - "$mergedfile"`;

if ($? == 0) {
    print color("green"), "Successfully merged to '$mergedfile'\n", color("reset");
    exit 0;
} else {
    print color("red"), "Merge was not successful\n", color("reset");
    unlink($mergedfile);
    exit 1;
}
