#!/bin/sh

progname=`basename "${0}"`

function error ()
{
    printf "${progname}: $*\n" >& 2;
    exit 1;
}

# Find the default cgc:
default_CGC="/usr/bin/cgc"
if ! test -x "${default_CGC}"; then
    default_CGC=`which cgc`
fi

# Find cgc:
CGC=${CGC:-"${default_CGC}"}

if ! test -x "${CGC}"; then
    error "cgc \"${CGC}\" command not found or not executable";
fi;

# Find the default nv40asm:
prefix="/usr/local/ps3dev/ppu"
exec_prefix="${prefix}"
bindir="${exec_prefix}/bin"
default_NV40ASM="${bindir}/nv40asm"
if ! test -x "${default_NV40ASM}"; then
    default_NV40ASM=`which nv40asm`
fi

# Find nv40asm:
NV40ASM=${NV40ASM:-"${default_NV40ASM}"}

if ! test -x "${NV40ASM}"; then
    error "nv40asm \"${NV40ASM}\" command not found or not executable";
fi;

CGC_opts=""
NV40_opts=""

shader=""
language=""
input=""
output=""

while test -n "$1"; do
    case "$1" in
	-v )
	    shader="v"
	    ;;
	-f )
	    shader="f"
	    ;;
	-x )
	    shift
	    language=`echo "$1" | tr '[A-Z]' '[a-z]'`
	    ;;
	-o )
	    shift
	    output="$1"
	    ;;
	-Xcgc )
	    shift
	    CGC_opts="$CGC_opts $1"
	    ;;
	-Xnv40asm )
	    shift
	    NV40ASM_opts="$NV40_opts $1"
	    ;;
	-* )
	    ;;

	*)
	    break
	    ;;
    esac

    shift
done

input="$1"

if test -z "$input"; then
    error "no input file";
fi

if ! test -f "$input"; then
    error "cannot read input file \"$input\"";
fi

if test -z "$shader"; then
    error "must specify program type: either vertex (-v) or fragment (-f)";
fi

if test -n "$language" -a "$language" != "cg" -a "$language" != "glsl"; then
    error "unknown language \"$language\"; must be either cg or glsl";
fi

input_filename=`basename "${input}"`
input_suffix=${input_filename##*.}
input_filename=`basename ${input_filename%.*}`
test "${input_filename}" == "${input_suffix}" && input_suffix=""

# Infer settings from input file suffix:
if test -n "${input_suffix}"; then

    # Language selection:
    if test -z "${language}"; then
	case "${input_suffix}" in
	    cg | vcg | fcg )
		language="cg"
		;;
	    glsl | vert | frag )
		language="glsl"
		;;
	esac
    fi
fi

# Infer settings from input file base:
if test -n "${input_filename}"; then

    # Output filename:
    if test -z "${output}"; then
	case "${shader}" in
	    v )
		output="${input_filename}.vpo"
		;;
	    f )
		output="${input_filename}.fpo"
		;;
	esac
    fi
fi

# Setup command line options:
case "$shader" in
    v )
	CGC_opts="-profile vp40 $CGC_opts"
	NV40ASM_opts="-v ${NV40ASM_opts}"
	shader_pretty="vertex"
	;;

    f )
	CGC_opts="-profile fp40 $CGC_opts"
	NV40ASM_opts="-f ${NV40ASM_opts}"
	shader_pretty="fragment"
	;;
esac

case "$language" in
    glsl )
	CGC_opts="-oglsl ${CGC_opts}"
	;;
esac

printf "compiling ${language} ${shader_pretty} program \"${input}\"..." >& 2
"${CGC}" ${CGC_opts} "${input}" | "${NV40ASM}" ${NV40ASM_opts} > "${output}"

exit 0
