#!/usr/bin/env sh

SAVED_PIPELINE_DIR="$DOTFILES_PATH/env/common/data/pipelines"
mkdir -p "$SAVED_PIPELINE_DIR"

if [ -n "${1+x}" ]; then
	pdir="$SAVED_PIPELINE_DIR/$1"; shift
	mkdir -p "$pdir"
	if [ -z ${1+x} ]; then
		td="$(mktemp -p "$pdir" -d "tmp_pipeline.XXXXXXXX")"
		# shellcheck disable=SC2064
		trap "rm -rf '$td'" EXIT
	else
		td="$pdir/$1"; shift
		mkdir -p "$td"
	fi
	transform="$pdir/transform"
else
	td="$(mktemp --tmpdir -d pipeline.XXXXXXXX)"
	transform="$td/transform"
	# shellcheck disable=SC2064
	trap "rm -rf '$td'" EXIT
fi

[ ! -e "$transform" ] && \
	printf "#!/usr/bin/env bash\n# you must save this buffer manually\n# for %s\n
base64" "${td}" > "$transform"

in="$td/in";   [ -n "${1+x}" ] && in="${1}"  && shift
out="$td/out"; [ -n "${1+x}" ] && out="${1}" && shift

# TODO: if no logging, log="/dev/null"
log="$td/log"
touch "$log"

chmod +x "$transform"

# TODO: saved inputs?
echo "Hello World" > "$in"

env PIPELINE_IN="$in" PIPELINE_TRANSFORM="$transform" PIPELINE_OUT="$out" nvim --cmd "source $DOTFILES_PATH/apps/neovim/scripts/pipeline.vim"