#!/bin/bash

# Set constants and defaults
SHP_NAME="shp"
SHP_VERSION="1.0.2"
DEFAULT_SHP_SHELL="/bin/bash -s"

# Usage message
usage()
{
    echo "Usage:" 1>&2
    echo "    ${SHP_NAME} [ file [ args ... ] ]" 1>&2
    echo "Options:" 1>&2
    echo "    --check     Check script syntax only (don't execute it)" 1>&2
    echo "    --dump      Dump generated shell script instead of executing it" 1>&2
    echo "    --shell     Specify alternate shell (default \`${DEFAULT_SHP_SHELL}')" 1>&2
    echo "    --help      Display this help message and exit" 1>&2
    echo "    --version   Display version and exit" 1>&2
}

# Show version
show_version()
{
    echo "${SHP_NAME} version ${SHP_VERSION}"
}

# Log functions
log()
{
    echo ${SHP_NAME}: ${1+"$@"} 1>&2
}

verbose_log()
{
    if "${VERBOSE}"; then
        echo ${SHP_NAME}: ${1+"$@"} 1>&2
    fi
}

# Error function
errout()
{
    log ${1+"$@"}
    exit 1
}

# Bail on errors
set -e

# Parse flags passed in on the command line
SHP_CHECK="false"
SHP_DUMP="false"
SHP_SHELL="${DEFAULT_SHP_SHELL}"
while [ ${#} -gt 0 ]; do
    case "$1" in
        -h|--help)
            usage
            exit
            ;;
        --check)
            shift
            SHP_CHECK="true"
            ;;
        --dump)
            shift
            SHP_DUMP="true"
            ;;
        --shell)
            shift
            shift
            SHP_SHELL="$1"
            ;;
        --version)
            show_version
            exit
            ;;
        -h|--help)
            usage
            exit
            ;;
        --)
            shift
            break
            ;;
        -?*)
            errout "unrecognized flag \`${1}'"
            ;;
        *)
            break
            ;;
    esac
done

# Get script file (if any)
SHP_SCRIPT=""
if [ $# -gt 0 ]; then
    SHP_SCRIPT="$1"
    shift
fi  

# Dump?
if [ "${SHP_DUMP}" = 'true' ]; then
    exec /usr/bin/gawk -f /usr/share/shp/shp.awk ${SHP_SCRIPT}
fi

# Check?
if [ "${SHP_CHECK}" = 'true' ]; then
    SHP_SHELL="${SHP_SHELL} -n"
fi

# Run
/usr/bin/gawk -f /usr/share/shp/shp.awk ${SHP_SCRIPT} | exec ${SHP_SHELL} ${1+"$@"}

