#!/bin/bash
# insb - in sandbox, run a command using automatically located files
# Copyright (C) 2010 - 2019 FARGOS Development, LLC
# $Id$
# Invokes a commmand using file names found within the same point of
# the directory hierarchy across the chain of sandbox backing tree.
# Example: assuming file1.txt does not exist in the local sandbox directory,
# then:  insb vi file1.txt
# will open file1.txt file in first corresponding location found in
# the backing tree chain if it exists, otherwise it would pass file1.txt
# as-is to vi for creating the file in the current directory.

# PORTABILITY NOTE: this uses arrays to preserve the structure of each
# command line token.
# Since bash was chosen as the implementation target, native arithmetic
# expressions are used.

originDir=`dirname $0`
targetCmd=""

declare -a argList # this will be an array
argCount=0


while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		# fall out, usage statement handled at bottom
		break
		;;
	-*)	# copy arguments as-is
		argCount=$(( argCount + 1 ))
		argList[${argCount}]="${1}"
		;;
	%*)	# use argument as-is, minus the "%" prefix
		asIs="${1:1}"
		argCount=$(( argCount + 1 ))
		argList[${argCount}]="${asIs}"
		;;
	*)	# treat as file and try to resolve it
		if test -z "${targetCmd}"
		then
			targetCmd="${1}"
		else
			realFile=`${originDir}/findFileInSB -all ${1}`
			argCount=$(( argCount + 1 ))
			if test -n "${realFile}"
			then
				# get rid of any ".." so references through
				# nonexistent directories work
				trueFile=`readlink -m ${realFile}`
				argList[${argCount}]="${trueFile}"
			else # use as-is
				argList[${argCount}]="${1}"
			fi
		fi
	esac
	shift
done
if test -z "${targetCmd}"
then
	printf "usage: %s command fileName [...]\n" "${0}" >&2
	printf "  NOTES: arguments beginning with \"-\" are passed as-is.\n" >&2
	printf "  If a fileName begins with \"%%\", the fileName portion is used as-is.\n" >&2
	printf "  If a fileName begins with \"@\", the local sandbox is not searched.\n" >&2
	printf "  This is useful to compare local vs. backing tree files:\n" >&2
	printf "      insb diff source.c @source.c\n" >&2
	exit 1
fi
exec "${targetCmd}" "${argList[@]}"
