#!/usr/bin/env nix-shell
#! nix-shell -i bash --pure
#! nix-shell -p bash pdftk inkscape gnused coreutils file

# Utility to write over a PDF file pages

# TODO Inkscape vodoo: Put the original in its own layer and skip when merging

orig_path="$1"

orig_dir="$(dirname "$orig_path")"
orig_file="$(basename "$orig_path")"
orig_ext="${orig_file##*.}"
orig_name="${orig_file%.*}"

wdir_file="${orig_name}_src.${orig_ext}"
wdir_path="${orig_dir}/${wdir_file}"

if [ -d "$wdir_path" ]
then
    echo "Source directory $wdir_path found"
    ls "${wdir_path}/"*"_og.pdf" | while read page_orig_path
    do
        page_stmp_svg="$(echo "$page_orig_path" | sed 's|_og\.pdf$|_fg\.svg|')"
        page_stmp_pdf="$(echo "$page_orig_path" | sed 's|_og\.pdf$|_fg\.pdf|')"
        page_fin_pdf="$(echo "$page_orig_path" | sed 's|_og\.pdf$|_fin\.pdf|')"
        if [ -f "$page_stmp_svg" ]
        then
            echo "Processing $page_orig_path (applying stamp)"
            inkscape "$page_stmp_svg" --export-filename "$page_stmp_pdf"
            pdftk "$page_orig_path" stamp "$page_stmp_pdf" output "$page_fin_pdf"
        else
            echo "Processing $page_orig_path (copying)"
            cp "$page_orig_path" "$page_fin_pdf"
        fi
    done
    echo "Merging everything back to ${orig_path}."
    pdftk "${wdir_path}/"*"_fin.pdf" output "$orig_path"
    echo "Deleting temporary files."
    rm "${wdir_path}/"*"_fin.pdf" "${wdir_path}/"*"_fg.pdf"
    echo "Done."
elif [ -f "$orig_path" ]
then
    if [ "$(file --mime-type --brief "$orig_path")" != "application/pdf" ]
    then
        echo "${orig_path}: not a PDF file"
        exit 1
    fi
    echo "Creating source directory $wdir_path with original pages and template SVGs"
    mkdir "$wdir_path"
    pdftk "$orig_file" burst output "${wdir_path}/${orig_name}_%03d_og.pdf"
    ls "${wdir_path}/"*"_og.pdf" | while read page_orig_path
    do
        page_stmp_svg="$(echo "$page_orig_path" | sed 's|_og\.pdf$|_fg\.svg|')"
        echo "Processing $page_orig_path"
        inkscape "$page_orig_path" --export-plain-svg --export-filename "$page_stmp_svg"
    done
    echo "Done. Make sure to edit in a a new layer in Inkscape and hide the original one."
else
    echo "${orig_path}: no such file or directory"
    exit 1
fi