#!/bin/sh
#
# ---
# see: https://github.com/deathbeam/dotfiles

# scriptpath=$(dirname "$(readlink -f "$0")")

file_args=$(mktemp "${TMPDIR:-/tmp}"/fzfmenu_args.XXXXXX)
file_choices=$(mktemp "${TMPDIR:-/tmp}"/fzfmenu_choices.XXXXXX)
TITLE=""

case "$(uname -s)" in
  Darwin)
    TERM_CLASS=""
    ;;
  *)
    TERM_CLASS="--class"
    if [ "${TERMINAL-}" = "st" ]; then
      TERM_CLASS="-n"
    elif [ "${TERMINAL-}" = "foot" ] || [ "${TERMINAL-}" = "footclient" ]; then
      TERM_CLASS="-a"
    fi
    ;;
esac

kill_old() {
  mypid=$$
  same=""
  others=""
  while read -r pid cmdline; do
    [ "${pid}" = "${mypid}" ] && continue
    if echo "${cmdline}" | grep -q -- "-p ${TITLE}"; then
      same="${pid}"
    else
      others="${others} ${pid}"
    fi
  done < <(pgrep -af fzfmenu)
  [ -n "${same}" ] && kill "${same}" && exit 0
  [ -n "${others}" ] && kill "${others}"
}

# kill_old() {
#   pgrep -x fzfmenu | grep -v "^$$\$" | xargs kill >/dev/null 2>&1
# }

scan_args() {
  while IFS= read -r line; do
    echo "${line}"
  done
  [ -n "${line}" ] && echo "${line}"
}

show() {
  while IFS= read -r line; do
    echo "${line}"
  done <"${file_choices}"
}

run_menu() {
  scan_args >"${file_args}"
  kill_old
  prompt "$@"
  show
}

prompt() {
  : >"${file_choices}"
  ${TERMINAL} "${TERM_CLASS-}" shellmenu -T "${TITLE}" \
    -e "${SHELL}" -c "
      exec fzf \
          --no-border \
          --margin 0,0 \
          --preview-window=border-sharp:wrap \
          --no-separator \
          --info=inline-right \
          --cycle \
          --print-query \
          --no-multi \
          --reverse \
          ${PROMPT} ${QUERY} $* < ${file_args} | tail -n 1 >! ${file_choices}
  " &
  pid=$!
  # shellcheck disable=SC2064
  trap "kill -TERM ${pid}" TERM
  wait "${pid}"
  [ -s "${file_choices}" ] || exit 1
}

main() {
  while true; do
    case "$1" in
      -l) shift ;;
      -p)
        shift
        TITLE="$1" && PROMPT="--prompt \"$1 > \""
        ;;
      -q)
        shift
        QUERY="-q \"$1\""
        ;;
      *) break ;;
    esac
    shift
  done
  quoted_args=""
  if [ "$#" -gt 0 ]; then
    # quoted_args="$(printf "%q " "$@")"

    # shellcheck disable=SC2312
    escape() { printf "'%s'\\n" "$(printf '%s' "$1" | sed -e "s/'/'\\\\''/g")"; }
    quoted_args="$(escape "$@")"
    # quoted_args="$(printf %s "$@" | sed "s/'/'\\\\''/g")"
  fi
  run_menu "${quoted_args}"
}

trap 'rm -f "$file_args" "$file_choices"' EXIT
main "$@"
