#!/bin/bash

# smart application launcher that remembers often used apps
# define $1 to run in terminal
# selections are remembered per mode as frecency caches
# ($XDG_CACHE_HOME/instantmenu/smartrun[-terminal|-desktop])
# `--toast SECONDS` makes the launcher noninteractive for startup benchmarks.
TOAST_ARGS=()
TOAST_DMENU=""
if [ "$1" = "--toast" ]; then
    # a positive number of seconds, fractions allowed ("0" and "0.0" are useless)
    if [[ ! "$2" =~ ^[0-9]+([.][0-9]+)?$ ]] || [[ ! "$2" =~ [1-9] ]]; then
        echo "usage: instantmenu_smartrun [--toast SECONDS] [desktop|terminal] [initial text]" >&2
        exit 2
    fi
    TOAST_ARGS=(--toast "$2")
    TOAST_DMENU=" --toast $2"
    shift 2
fi

if [ -n "$2" ] || [ -z "$1" ]; then
    CACHE="smartrun"
    RARGS="terminal"
    LARGS="desktop"
else
    if [ "$1" = "desktop" ]; then
        shift 1
        i3-dmenu-desktop --dmenu="instantmenu --prompt desktop --frecency-cache smartrun-desktop --left-command \"instantmenu_smartrun terminal\" --right-command \"instantmenu_smartrun\" --placeholder \"search apps\" --lines 10 --position center --insensitive --width 900 --border-width 4${TOAST_DMENU}"
        exit
    fi
    CACHE="smartrun-terminal"
    RARGS="desktop"
    LARGS=""
fi

# instantmenu ranks the executables by frecency and records the selection in
# the cache the moment it is printed
INITIAL=()
[ -n "$2" ] && INITIAL=(--initial-text "$2")

read -r SELECTION < <(instantmenu_path | sort -u |
    instantmenu \
        --frecency-cache "$CACHE" \
        --right-command "instantmenu_smartrun $RARGS" \
        --left-command "instantmenu_smartrun $LARGS" \
        --prompt "${1}" \
        --insensitive \
        --placeholder "search apps" \
        --lines 10 \
        --position center \
        --width 900 \
        --border-width 4 \
        "${INITIAL[@]}" "${TOAST_ARGS[@]}")

if [ -z "$SELECTION" ]; then
    echo "selection empty, exiting"
    exit
fi

# detached like instantmenu's own command spawns
if [ -z "$1" ]; then
    /bin/sh -c "$SELECTION" &>/dev/null &
else
    ~/.config/instantos/default/terminal -e "/bin/sh" -c "$SELECTION" &>/dev/null &
fi
