#!/bin/sh -e

# Copyright (c) 2011 Mathias Kende, Gabriel Kerneis
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# ramfs cannot swap, contrary to tmpfs
# it can also eat up all your RAM, be careful!
USE_RAMFS=0

die() {
  echo $1 >&2
  exit 1
}

findcmd() {
  which "$1" > /dev/null || \
    die "Couldn't find $1, please install ${2:-it} or fix your path."
}

usage="Usage: $0 [-r] input_file [output_file]"

while getopts "r" name
do
  case $name in
    r) USE_RAMFS=1;;
    ?) die "$usage"
  esac
done
shift $(($OPTIND - 1))

[ $# -lt 1 ] && die "$usage"

if [ $USE_RAMFS = "1" -a "$(whoami)" != root ]; then
  die "Sorry, you need to be root (to mount a ramfs)."
fi

findcmd split
findcmd dmtxwrite libdmtx-utils
findcmd md5sum
findcmd pdflatex

INPUT=$1
OUTPUT=${2:-${INPUT}.pdf}

TMP_DIR=`mktemp -d`

# _ is a special character in LaTex
TEX_NAME=$(basename "$INPUT" | sed 's/_/\\_/')

# LaTex does not like multiple dots in filenames
# when looking for the extension
BASENAME=$(basename "$INPUT"|tr . -)
BASE=$TMP_DIR/$BASENAME

if [ $USE_RAMFS = "1" ]; then
  mount -t ramfs none $TMP_DIR ||
    (rmdir $TMP_DIR; die "Could not create ramfs.")
else
  findcmd shred
fi

on_exit ()
{
  if [ $USE_RAMFS = "1" ]; then
    umount $TMP_DIR
  else
    echo "Shreding temporary files..."
    find $TMP_DIR -type f -execdir shred -u '{}' \;
  fi
  rm -rf $TMP_DIR
}
trap on_exit EXIT

# Remove -d if you have a very big file
# (but is it reasonable to print it, then?)
split -d -a 2 -C 1500 "$INPUT" "${BASE}_" ||
  die "Could not create parts"

cat > "${BASE}.tex" << EOF
\documentclass[10pt,a4paper]{article}
\sloppy

\usepackage[a4paper,includehead,includemp=false]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{float}
\usepackage[figurename=Part]{caption}

\geometry{top=0.5cm}
\geometry{bottom=0.5cm}
\renewcommand{\floatpagefraction}{1}
\renewcommand{\textfraction}{0}
\setcounter{totalnumber}{8}
\renewcommand{\topfraction}{1}
\renewcommand{\bottomfraction}{1}

\newcommand{\filetitle}{$TEX_NAME}

\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{\filetitle}
\fancyhead[R]{\textbf{\thepage}}

\restylefloat{figure}

\begin{document}
\vspace*{-12mm}
\noindent File: $TEX_NAME\\\\
Parts: $(find $TMP_DIR -name "${BASENAME}_*" | wc -l)\\\\
MD5: $(md5sum -b "$INPUT" | cut -f 1 -d ' ')\\\\
\vspace*{-06mm}
EOF

find $TMP_DIR -name "${BASENAME}_*" | sort -g | while read f
do
  echo Converting $f
  dmtxwrite -d 5 -m 10 -e 8 -f PDF -s 144x144 "$f"  > "$f.pdf"
  cat >> "${BASE}.tex" << EOF
\begin{figure}[H]
    \centering
    \includegraphics[width=0.85\textwidth]{"$f".pdf}
    \vspace*{-4mm}
    \caption{md5 = $(md5sum -b "$f" |cut -f 1 -d ' ')}
\end{figure}
\vspace*{-2mm}
EOF
done

cat >> "${BASE}.tex" << EOF
\end{document}
EOF

pdflatex -interaction=batchmode -output-directory $TMP_DIR "${BASE}.tex" >/dev/null

cp "${BASE}.pdf" "$OUTPUT"

echo File successfully generated: $OUTPUT


