#!/usr/bin/env bash

######################################################################
# Generates a .ghci config file for cardano-wallet.
# Use this if you want faster reloads across packages.
# Both this script and ghci need to be run from the nix-shell.
######################################################################

set -euo pipefail

. "$(dirname "$0")/cabal-lib.sh"

######################################################################
# Config file generation

make_ghci() {
  echo "-- Generated by $0 for version $(get_cabal_version)"
  echo "-- $(date)"
  echo

  ghci_flags | sed -e 's/^/:set /'

  cat <<EOF

:set prompt "λ "
:set -package pretty-simple
:set -interactive-print=Text.Pretty.Simple.pPrint

import Prelude
import System.Environment (setEnv, getEnv)
import System.Directory (getCurrentDirectory)

getCurrentDirectory >>= \d -> getEnv "PATH" >>= \p -> setEnv "PATH" (d ++ "$(get_bin_dir cardano-wallet exe:cardano-wallet):" ++ p)
EOF
}

######################################################################
# Main script

ghci=custom.ghci

echo "Generating $ghci. Some cabal builds may be necessary."

tmp=$(mktemp -d)
cleanup() { rm -rf "$tmp"; }
trap cleanup EXIT

make_ghci > "$tmp/.ghci"
mv "$tmp/.ghci" $ghci

symlink() {
  src="$1"
  target="$2"

  if [ ! -e "$target" ] || [ -L "$target" ]; then
    ln -vsf "$src" "$target"
  else
    echo "Refusing to overwrite $target - check the file then run:"
    echo "  ln -sf $src $target"
  fi
}

symlink "$ghci" .ghci
