#!/bin/bash
# Create the destination file and temporary files
file=original53.pdf;
newfile=$(basename $file .pdf)-2.pdf;
tmpfile=$(mktemp --suffix=.pdf);
blankfile=$(mktemp --suffix=.pdf);
cp -f $file $newfile;
cp -f $file $tmpfile;

# Find the number of pages
numberofpages=`pdftk $file dump_data | grep "NumberOfPages" | sed 's:.*\([0-9][0-9*]\).*:\1:'`;

# Insert blank pages until the number of pages is a multiple of 4
echo "" | ps2pdf -sPAPERSIZE=a4 - $blankfile;
while (( $numberofpages % 4 != 0 )); # DIFFERENCE: %% instead of % since % is used by Nautilus-Actions for special parameters
do 
  ((numberofpages++));
  pdftk A=$newfile B=$blankfile cat A B output $tmpfile;
  cp -f $tmpfile $newfile;
done;

# Reorder every 4 pages of a PDF following the permutation 1234 -> 1342
a=0;
neworder=$(
  while [ $a -lt $numberofpages ];
  do 
    echo -n "$(($a + 1)) $(($a + 3)) $(($a + 4)) $(($a + 2)) ";
    ((a+=4));
  done;
);
pdftk $tmpfile cat $neworder output $newfile;
