#!/bin/bash -u
#
# Copyright 2020 Misha Brukman
# SPDX-License-Identifier: Apache-2.0
# https://misha.brukman.net/blog/2020/04/add-a-repl-to-any-cli-tool/

if ! [ -n "${REPL_USING_RLWRAP:-}" ]; then
	# Use `rlwrap` if available.
	if which rlwrap >/dev/null 2>&1; then
		exec env REPL_USING_RLWRAP=1 rlwrap "$0" "$@"
	else
		echo 'Install `rlwrap` and re-run this script to get command history.'
	fi
fi

echo "This is the Go REPL; exit via Ctrl-D."

while true; do
	echo -n "-> "
	read command || break

	tmpfile=$(mktemp)
	printf "package main\n$command" > $tmpfile
	cd $(dirname "$tmpfile")
	go run $(basename "$tmpfile")
	rm $tmpfile
done

# Add a blank line at the end for a clean prompt when exiting.
echo
