declare -a default_ghc_packages=(pretty-simple lens)

ghc-with-packages () {
  declare -a packages=()
  local GHC_COMMAND=${GHC_COMMAND:-"ghc"}
  packages+=$default_ghc_packages
  local exit=0 stop_args
  while [[ ! -z "$1" && -z "$stop_args" ]]; do
      local opt="$1"
      shift 1
    case "$opt" in
        "--")
            stop_args=1
            ;;
        "-p")
            while [[ ! -z "$1" && "$1" != -* ]]; do
                packages+=("$1")
                shift 1
            done
            ;;
      *|"-h")
        exit=1
        ;;
    esac
  done

  local pretty_simple

  for p in "$packages"; do
      if [[ "$p" = "pretty-simple" ]]; then
          pretty_simple="-interactive-print=Text.Pretty.Simple.pPrint"
      fi
  done

  if [[ "$exit" -eq 0 ]]; then
      # echo "packages: ${packages[@]}"
      # echo "args: $*"
      local pkgs="${packages[@]}"
      nix-shell \
          -p "haskellPackages.ghcWithPackages (p: with p; [ $pkgs ])" \
          --run "$GHC_COMMAND $pretty_simple $*"
  else
      echo >&2 "Usage: ghci-with-packages [-p packages…] [-- ghci-options]"
      return $exit
  fi
}
export -f ghc-with-packages

ghci-with-packages () {
    GHC_COMMAND=ghci ghc-with-packages "$@"
}
export -f ghci-with-packages
