#!/bin/sh

# jamin-wrapper
#
# - Introduces an '-X' arg that will run jamin under gdb
#
# - When no jam file was specified and the user has not created a
#   ~/.jamin/default.jam file, adds an arg for loading the default
#   jam file from jamin's defualt.jam example, using XDG_RUNTIME_DIRS
#
# - If LADSPA_PATH is not already set in the environment, ensures
#   LADSPA_PATH will be set for the location of ladspa-swh-plugins.
#   This environment variable is used within jamin

OPTSTR="Xf:hj:n:s:c:rpil:vVdFTtgD"
PARSED=$(getopt -n jamin-wrapper -o ${OPTSTR} -- "$@");
RS=$?
if [ ${RS} -ne 0 ]; then
    exec jamin -h
fi
eval set -- "${PARSED}"
declare -a ARGS

NEED_DEFAULT_JAM=1
NEED_GDB=0

while true; do
    case "$1" in
        -f)
            NEED_DEFAULT_JAM=0
        ;;
        -X)
            NEED_GDB=1
            shift
            continue
        ;;
        --)
            shift
            break
        ;;
        *)
        ;;
    esac
    ARGS[${#ARGS[@]}]="$1"
    shift
done


if [ "${NEED_DEFAULT_JAM}" -eq 1 ] &&
    ! [ -e "${HOME}/.jamin/default.jam" ]  &&
    [ -n "${XDG_DATA_DIRS}" ]; then
    DEFAULT_JAM=$(echo "$XDG_DATA_DIRS" | awk '
        BEGIN {RS=":"}
        // {
            test_jam = ($1 "/jamin/examples/default.jam");
            if (getline nop < test_jam >= 0) { print test_jam; exit }
        }')
    if [ -n "${DEFAULT_JAM}" ]; then
        ARGS[${#ARGS[@]}]="-f"
        ARGS[${#ARGS[@]}]="${DEFAULT_JAM}"
    fi
fi


if [ "${NEED_GDB}" -ne 0 ]; then
    set -x
    LADSPA_PATH="${LADSPA_PATH}" exec gdb --args jamin "${ARGS[@]}" "${@}"
else
    set -x
    LADSPA_PATH="${LADSPA_PATH}" exec jamin "${ARGS[@]}" "${@}"
fi
