#!/bin/bash

usage() {
    cat <<EOF
Usage:
    $0 [-o|--output <output>] <spec_file>

    Preprocess the given spec file and either print the result
    to stdout or to a file. If the source spec_file contains
    any macros that produce files, these will be put into CWD.
    NOTE: you should trust the spec files you are preprocessing

Options:
    -h, --help             Print help
    -o|--output <path>     Puts the result to a file on the given path.
                           If the given path is a directory, basename of
                           the <spec_file> is used to complete it.

Arguments:
    spec_file              Path to the spec file to be preprocessed
EOF
}

OUTPUT=""
SPEC_FILE=""

while [ -n "$1" ] ; do
    case "$1" in
    -h|--help)
        usage
        exit 0
        ;;
    -o|--output)
        shift
        OUTPUT="$1"
        ;;
    *)
        SPEC_FILE="$1"
        ;;
    esac
    shift
done

if [ -z "$SPEC_FILE" ]; then
    usage
    exit -1
fi

if [ -n "$OUTPUT" ]; then
    tmpfile="$(mktemp)"
    cat "$SPEC_FILE" | preproc -s /usr/lib/rpkg.macros.d/all.bash -e INPUT_DIR_PATH="$(dirname "$SPEC_FILE")" -e OUTDIR="$(pwd)" > "$tmpfile"
    if [ -d "$OUTPUT" ]; then
        OUTPUT="$OUTPUT"/"$(basename "$SPEC_FILE")"
    fi
    mv "$tmpfile" "$OUTPUT"
else
    cat "$SPEC_FILE" | preproc -s /usr/lib/rpkg.macros.d/all.bash -e INPUT_DIR_PATH="$(dirname "$SPEC_FILE")" -e OUTDIR="$(pwd)"
fi
