#!/bin/bash

# smart application launcher that remembers often used apps
# define $1 to run in terminal
if [ -n "$2" ] || [ -z "$1" ]; then
    LIST="$HOME/.cache/instantmenuhist"
    RARGS="terminal"
    LARGS="desktop"
else
    if [ "$1" = "desktop" ]; then
        shift 1
        i3-dmenu-desktop --dmenu='instantmenu -p desktop -lc "instantmenu_smartrun terminal" -rc "instantmenu_smartrun" -q "search apps" -l 10 -c -i -w -1 -h -1 -bw 4'
        exit
    fi
    LIST="$HOME/.cache/instanttermmenuhist"
    RARGS="desktop"
    LARGS=""
fi

if [ -n "$2" ]; then
    # read history and path
    # put in initial text
    read -r SELECTION < <({
        tac "$LIST"
        instantmenu_path | sort -u
    } | perl -nE '$seen{$_}++ or print' |
        instantmenu -rc "instantmenu_smartrun $RARGS" -lc "instantmenu_smartrun $LARGS" \
            -p "${1}" -i -f -q "search apps" -l 10 -c -w -1 -h -1 -bw 4 -it "$2")
else

    # read history and path
    read -r SELECTION < <({
        tac "$LIST"
        instantmenu_path | sort -u
    } | perl -nE '$seen{$_}++ or print' |
        instantmenu -rc "instantmenu_smartrun $RARGS" -lc "instantmenu_smartrun $LARGS" \
            -p "${1}" -i -f -q "search apps" -l 10 -c -w -1 -h -1 -bw 4)
fi

# check if the application doesn't exist (indicated by exit code 1 and short runtime)

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

a="$(TZ=UTC0 printf '%(%s)T\n' '-1')" ### `-1`  is the current time
if [ -z "$1" ]; then
    EXITSTATUS=$({
        /bin/sh -c "$SELECTION" &>/dev/null && echo "$?"
    })
else
    EXITSTATUS=$({
        ~/.config/instantos/default/terminal -e "/bin/sh" -c "$SELECTION" &>/dev/null && echo "$?"
    })
fi

elapsedseconds=$(($(TZ=UTC0 printf '%(%s)T\n' '-1') - a))

if [ "$elapsedseconds" -gt 5 ] || [ "$EXITSTATUS" = 0 ]; then
    [ -e "$HOME/.cache" ] || mkdir "$HOME/.cache"
    echo "$SELECTION" | tee -a "$LIST"
else
    echo "error in running $SELECTION: skipping history"
fi

# max history size
if [ "$(wc -l "$LIST" | grep -o '^[^ ]*')" -gt 1300 ]; then
    head -1000 <"$LIST" | tee "${LIST}2"
    cat "${LIST}2" >"$LIST"
fi
