#!/bin/bash

start(){ xterm -title "${1^}" -e bash -ic "$@" & }
menu(){ dmenu.sh -p "$@"; }
browser(){ brave-browser "$@" || iridium-browser "$@" || firefox "$@"; }
search(){ luakit -n "https://${*// /+}"; }

if [[ ! $DISPLAY || $TMUX ]]; then
    start(){ "$@"; }
    menu(){ fzf; }
    browser(){ start elinks "${@:2}"; }
    search(){ browser 0 "https://${*// /+}"; }

    gvim(){ start vim; }
    pavucontrol(){ start ncpamixer; }

    [[ $TMUX ]] && start(){ tmux neww -n $1 "$@"; }
fi

case ${1,,} in
    files) start ranger;;
    browser) browser --new-window lexa.by;;
    editor) gvim;;
    shell) start tm;;

    music) start mocp;;
    calendar) start calcurse;;
    contacts) start abook;;

    mail) start mutt;;
    news) start newsboat;;
    torrents) start transmission-remote-cli;;

    apps) xfce4-appfinder;;
    mixer) pavucontrol;;
    network) start nmtui;;
    bloge) EDITOR='gvim -f' start "blo.sh $2";;

    start) $0 $($0 | sed 's/.*/\u\0/' | menu Start);;
    audio) audio.sh $(audio.sh | menu Device | cut -f 2);;
    windows) wmctrl -ia "$(wmctrl -l | menu Windows -l 20)";;

    \!*) $0 ddg "$*";;
    ddg) search "duckduckgo.com/?q=${*:2}";;
    man) search "manned.org/browse/search?q=${*:2}";;
    wiki) search "ru.m.wikipedia.org/wiki?search=${*:2}";;

    '') grep -o '^\s*\w*)' $0 | sed 's/[) ]//g';;
    *) start "$1";;
esac
