#!/bin/sh
#
#  /usr/bin/dosbox  --  part of DOSBox package
#
#  Wrapper for running actual DOSBox binary
#  with system-wide settings.
#

dir0=`dirname $0`

BIN_PATH=$dir0/dosbox.bin
CONF_NAME=dosbox.conf
CONF_DIRS="$HOME/.dosbox /usr/local/etc/dosbox /etc/dosbox"

declare CONF_PATH

if [ "$1" = "--dry-run" ]; then
    : ${doit:=echo}
    $doit : Enable dry running...
    shift
fi

function report_error()  # args are parts of error message
{
    echo "Error: $*!" 1>&2
    return 1
}

function run_binary()  # args are passed to binary
{
    $doit : Run binary, args = "$@"
    if [ ! -x "$BIN_PATH" ]; then
	report_error "cannot find binary $BIN_PATH"
	return 1
    fi
    if [ -z "$DISPLAY" ]; then
	report_error "X Window is not running, DISPLAY variable is empty"
	return 1
    fi
    $doit "$BIN_PATH" "$@"
}

function present_switch()  # $1 = switch to find, $2* = cmdline. Returns boolean
{
    local sw=$1
    shift
    for c in "$@"; do
	[ "$c" = "$sw" ] && return 0
    done
    $doit : Switch \"$sw\" is not presented.
    return 1
}

function assign_conf_name()  # no args, assigns CONF_PATH
{
    for d in $CONF_DIRS; do
	CONF_PATH="$d/${CONF_NAME}"
	: $doit : Test configuration file $CONF_PATH
	[ -r "$CONF_PATH" ] && return 0
    done
    return 1
}

function main()
{
    if present_switch "-conf" "$@"; then
	run_binary "$@"
    elif present_switch "--skip" "$@"; then
	run_binary "$@"
    elif assign_conf_name; then
	$doit : Found configuration file "$CONF_PATH"
	run_binary -conf "$CONF_PATH" "$@"
    else
	run_binary "$@"
    fi
}

present_switch "--no-main" "$@" || main "$@"

## EOF ##
