#!/usr/bin/env bash

if [ $# -eq 0 ]; then
	echo "Usage: withenv <env-file> [env-file2] ... -- <command> [args]" >&2
	exit 1
fi

script_dir=$(dirname "$0")

env_files=()
cmd_args=()
parsing_files=true

for arg in "$@"
do
	if [ "$arg" = "--" ]
	then
		parsing_files=false
		continue
	fi

	if $parsing_files
	then
		env_files+=("$arg")
	else
		cmd_args+=("$arg")
	fi
done

if [ ${#env_files[@]} -eq 0 ]; then
	echo "Error: No env files provided" >&2
	echo >&2
	echo "Usage: withenv <env-file> [env-file2] ... -- <command> [args]" >&2
	exit 1
fi

if [ ${#cmd_args[@]} -eq 0 ]; then
	echo "Error: No command specified after --" >&2
	echo >&2
	echo "Usage: withenv <env-file> [env-file2] ... -- <command> [args]" >&2
	exit 1
fi

data=$($script_dir/upfind "${env_files[@]}" | xargs $script_dir/show) || exit $?

(
	set -a
	eval "$data"
	set +a
	exec "${cmd_args[@]}"
)
