#!/bin/bash

# src: https://github.com/manjaro/packages-community/blob/master/dmenu-manjaro/dmenu_recency

# Originally based on code by Dieter Plaetinck.
# Pretty much re-written by Mina Nagy (mnzaki)
# Edited by Chrysostomus to create/source .dmenurc

if ! [ -f "$HOME/.dmenurc" ]; then
	cp /usr/share/dmenu/dmenurc $HOME/.dmenurc
fi
. $HOME/.dmenurc

if [ -z "$TERMINAL_CMD" ]; then
  if [ "$(which terminal)" ]; then
  TERMINAL_CMD="terminal -e"
  elif [ "$(which urxvt)" ]; then
  TERMINAL_CMD="urxvt -e"
  elif [ "$(which termite)" ]; then
  TERMINAL_CMD="termite -e"
  elif [ "$(which terminator)" ]; then
  TERMINAL_CMD="terminator -e"
  elif [ "$(which gnome-terminal)" ]; then
  TERMINAL_CMD="gnome-terminal -e"
  elif [ "$(which lxterminal)" ]; then
  TERMINAL_CMD="lxterminal -e"
  elif [ "$(which sakura)" ]; then
  TERMINAL_CMD="sakura -e"
  elif [ "$(which xfce4-terminal)" ]; then
  TERMINAL_CMD="xfce4-terminal -e"
  elif [ "$(which xterm)" ]; then
  TERMINAL_CMD="xterm -e"
  fi
fi

dmenu_cmd="dmenu $DMENU_OPTIONS"
max_recent=199 # Number of recent commands to track

cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/dmenu-recent"
recent_cache="$cache_dir/recent"
rest_cache="$cache_dir/all"
known_types=" background terminal terminal_hold "

config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/dmenu-recent"
mkdir -p "$cache_dir"
mkdir -p "$config_dir"
touch "$recent_cache"

# Without this, it won't remember $type
GREP_OPTIONS='--color=never'

IFS=:
if stest -dqr -n "$rest_cache" $PATH 2>/dev/null; then
    stest -flx $PATH | sort -u | grep -vf "$recent_cache" > "$rest_cache"
fi

IFS=" "
cmd=$(cat "$recent_cache" "$rest_cache" | $dmenu_cmd -p run: "$@") || exit

if ! grep -qx "$cmd" "$recent_cache" &> /dev/null; then
    grep -vx "$cmd" "$rest_cache" > "$rest_cache.$$"
    if -s "$rest_cache.$$"; then
        mv "$rest_cache.$$" "$rest_cache"
    else
        rm "$rest_cache.$$"
    fi
fi

if [[ ! $cmd == *[[]* ]]; then
    echo "$cmd" > "$recent_cache.$$"
    grep -vx "$cmd" "$recent_cache" | head -n "$max_recent" >> "$recent_cache.$$"
    mv "$recent_cache.$$"  "$recent_cache"
fi

# Figure out how to run the command based on the command name, disregarding
# arguments, if any.
word0=${cmd%% *}
match="^$word0$"

get_type () {
    while type=$(echo $known_types | xargs -n1 | $dmenu_cmd -p Type:); do
        [[ $known_types =~ " $type " ]] || continue
        echo "$word0" >> "$config_dir/$type"
        break
    done
    echo $type
}

if ! type=$(grep -lx "$match" -R "$config_dir"); then
    type=$(get_type)
else 
    type=${type##*/}
    if ! [[ $known_types =~ " $type " ]]; then
        rm "$config_dir/$type"
        type=$(get_type)
    fi
fi

[[ "$type" = "background" ]] && exec $cmd
[[ "$type" = "terminal" ]] && exec $TERMINAL_CMD "$cmd"
[[ "$type" = "terminal_hold" ]] &&
    exec $TERMINAL_CMD sh -c "$cmd && echo Press Enter to kill me... && read line"
