#!/bin/sh
#
# delver - run Golang debugger on a reposurgeon module
#
# Accepts an optional module argument, which is
# only interpreted if it is not called inside
# a module directory.
#
# Based on this recipe:
# https://github.com/go-delve/delve/issues/1982
#
# This script spawns a headless delve instance to
# run reposurgeon, and its own terminal-emulator
# window for controls.  The reason this is required
# is that a non-headless delve instance messes with stdin,
# which becomes unavailable to the spawned program.
#
# To actually start reposurgeon, type 'continue' or 'c'
# to the delver control window.

# Set the terminal emulator to use here. It must execute following
# arguments as a command within the terminal.  Note: we can't use the
# magic x-terminal-emulator link in the Debian preferences system
# because we don't have any way to know whether it needs its final
# option to be -e or -x. Note when testing new emulators; setting
# the title may fail unless you give it a command to run.
config=~/.config/delver/delver.init
if [ -f "$config" ]
then
    # Expect this, if present, to set TERMINAL
    # shellcheck disable=SC1090
    . $config
elif command -v rxvt >/dev/null 2>&1
then
    TERMINAL="rxvt -T Delve-controls -e"
elif command -v xfce4-terminal >/dev/null 2>&1
then
    TERMINAL="xfce4-terminal -T Delve-controls -x"
elif command -v gnome-terminal >/dev/null 2>&1
then
    # The --title option is not documented 
    TERMINAL="gnome-terminal --title Delve-controls -x"
elif command -v konsole >/dev/null 2>&1
then
    TERMINAL="konsole -e"
elif command -v xterm >/dev/null 2>&1
then
    TERMINAL="xterm -T Delve-controls -e"
else
    echo "delver: cannot find a usable terminal emulator" >&2
    exit 1
fi

# If this script is called from the test or source code directories,
# pop up to the top level so we resolve paths from a known location.
case $(basename "$PWD") in
    reposurgeon) MODULE=./${1:-surgeon};;
    test) cd ..;  MODULE=./${1:-surgeon};;
    surgeon|cutter|mapper) cd ..; MODULE=./$(basename PWD);;
    *) echo "Where am I?" >&2; exit 1;;
esac

# Mechanism starts here.
killall dlv 2>/dev/null
(sleep 1; ${TERMINAL} dlv connect 127.0.1:3100) &
serverpid=$!
trap 'kill ${serverpid} 2>/dev/null' EXIT HUP INT QUIT TERM
dlv debug "${MODULE}" --headless --listen 127.0.0.1:3100

# By default delve uses dark-blue highlighting for source-line
# numbers, which doesn't play so well on a black background.  To fix
# this, modify the configuration file at ~/.config/dlv/config.yml and
# 3/4 with a setting line something like "source-list-line-color: 37",
# using foreground colors defined here:
# https://en.wikipedia.org/wiki/ANSI_escape_code#Color

#end

