#!/bin/sh

# Helper script to export LaTeX/knitr templates for new documents
# Copyright (c) 2009-2026 Benjamin Mako Hill <mako@atdot.cc>
# Released under the GPLv3 or later.

set -e

CURDIR=$(pwd)

usage() {
    echo "Usage: $(basename "$0") <type> <directory>"
    echo "Types: paper, memo, knitr, letter"
    exit 1
}

[ -n "$1" ] && [ -n "$2" ] || usage

TYPE="$1"
DEST="$2"

case "$TYPE" in
    paper)
        REPO="$HOME/tex/cdsc_tex"
        BRANCH="master"
        TEMPLATE="paper_template"
        EXT="tex"
        ;;
    memo)
        REPO="$HOME/tex/cdsc_tex"
        BRANCH="master"
        TEMPLATE="memo_template"
        EXT="tex"
        ;;
    knitr)
        REPO="$HOME/tex/cdsc_tex"
        BRANCH="knitr"
        TEMPLATE="paper_template"
        EXT="Rtex"
        ;;
    letter)
        REPO="$HOME/tex/cdsc_tex"
        BRANCH="master"
        TEMPLATE="letter_template"
        EXT="tex"
        ;;
    *)
        echo "error: unknown type '$TYPE'"
        usage
        ;;
esac

if [ -e "$DEST" ]; then
    echo "error: '$DEST' already exists"
    exit 1
fi

WORK_DIR=$(mktemp -d)
cd "$REPO"
git archive --format=tar "$BRANCH" "$TEMPLATE" | tar x --strip=1 -C "$WORK_DIR"
cd "$CURDIR"
mv "$WORK_DIR" "$DEST"
cd "$DEST"
mv "text.$EXT" "$(basename "$DEST").$EXT"
