#!/usr/bin/env bash

command -v xdot > /dev/null || { echo "Please install xdot before using this script"; exit 1; }

main="vehicle/planner/decision/ltl2_utils/ltl_query/ltl_query_main"
decision_primitives_pbtxt="vehicle/planner/decision/decision_primitives.pbtxt"

xdot_pid_file="$(mktemp /tmp/xdot_pid.XXXXXX.txt)"
graph_path="$(mktemp /tmp/graph.XXXXXX.dot)"
echo "digraph G {}" > "$graph_path"

block_on_pid() {
  tail --pid="$1" -f /dev/null
}

keepalive_xdot() {
  # ensures that xdot keeps running till the $xdot_pid_file
  # exists on the disk. When we want to close xdot, we remove
  # the $xdot_pid_file and send SIGINT to the pid in that file
  while [[ -f "$xdot_pid_file" ]]; do
    xdot "$graph_path" &
    xdot_pid="$!"
    echo "$xdot_pid" > "$xdot_pid_file"
    block_on_pid "$xdot_pid"
  done
}

keepalive_xdot &
$main --config="$decision_primitives_pbtxt" --out="$graph_path"

# cleanup
xdot_pid=$(cat "$xdot_pid_file")
rm "$xdot_pid_file"
kill -SIGINT "$xdot_pid"
echo "You can still view the graph at $graph_path"
