#!/bin/bash

# by teknohog

# To make (drink)? labels, start with a single PDF/PNG/JPEG and repeat
# it into a NxN grid. Requires pdfjam.

# The input can now be a vector format to improve quality over the old
# TIFF workflow. Libreoffice's PDF export looks glitchy on Evince, but
# in fact on Acrobat and printout it is perfect, thus making 5x5 and
# even smaller grids viable :)

# Default number of rows and columns in grid
SIZE=5

LSOPT="--no-landscape"

SCALE=1

while getopts lms: opt; do
    case $opt in
	l)
	    LSOPT=""
	    ;;
	m)
	    # Make some margins for printing; at least 0.97 is OK for
	    # my HP LJ 6MP. This is not always needed so keep
	    # optional.
	    SCALE=0.97
	    ;;
	s)
	    SIZE=$OPTARG
	    ;;
    esac
done
shift $(($OPTIND - 1))

for INPUT in $@; do
    EXT=`echo $INPUT | sed -e 's/.*\.\([a-zA-Z0-9]*$\)/\1/'`
    
    # For simple symlinks, need just a name and no dir
    LINK_PREFIX=$(basename `mktemp`)

    # 2015-10-22 Non-square formations should also be possible,
    # e.g. 5x6. A single number will be treated as the side of a
    # square.

    if [ -n "$(echo $SIZE | grep x)" ]; then
	NUP=$SIZE
	LNUM=$(echo $SIZE | sed -Ee 's/x/ /' | awk '{print $1*$2}')
    else
	NUP=${SIZE}x${SIZE}
	LNUM=$((SIZE*SIZE))
    fi
	
    # Input may or may not be a PDF, but the output always is
    OUTPUT=${INPUT//$EXT/label$NUP.pdf}
    
    for i in `seq 1 $LNUM`; do
	ln -s $INPUT $LINK_PREFIX$i.$EXT || exit
    done
    
    pdfnup --scale $SCALE --nup $NUP $LSOPT --outfile $OUTPUT ${LINK_PREFIX}*
    
    rm ${LINK_PREFIX}*
done
