#!/bin/bash

# this program reads a list of default applications from iconf
# and then symlinks them to the home config dir to be executed from there

echo "setting up default applications"

if [ -e ~/.config/instantos/default ]; then
    cd ~/.config/instantos/default || exit
    for i in ./*; do
        [ -L ./"$i" ] || continue
        if [ ! -e "$i" ]; then
            echo "link $i is broken, repairing"
            rm "$i"
        fi
    done
else
    mkdir -p ~/.config/instantos/default
fi

cd ~/.config/instantos/default || exit

XDGBROWSER="$(xdg-settings get default-web-browser)"
BROWSERLOCATION="$(grep -m 1 Exec </usr/share/applications/"$XDGBROWSER" | sed 's/Exec=*//g' | sed 's/[ ][^ ]*//')"

# symlink browser
if [ -e "$BROWSERLOCATION" ]; then
    echo "setting default browser to $BROWSERLOCATION"
    [ -e browser ] && rm browser
    ln -s "$BROWSERLOCATION" ./browser
fi

# apply the default setting for an application type, fallback to $2
setprogram() {
    [ -e "$1" ] && rm "$1"
    TEMPSETTING=$(iconf "$1:$2")
    echo "setting $1 to $TEMPSETTING"
    if command -v "$TEMPSETTING"; then
        PROGRAMPATH="$(command -v "$TEMPSETTING")"
        if [ -z "$PROGRAMPATH" ]; then
            echo "$TEMPSETTING not installed or not in PATH"
            return
        fi

        ln -s "$PROGRAMPATH" ./"$1"
    else
        echo "$TEMPSETTING" '"$@"' >"$1"
        chmod +x "$1"
    fi
}

setprogram terminal kitty
setprogram graphicaleditor code
setprogram appmenu appmenu
setprogram browser firefox
setprogram filemanager nautilus
setprogram systemmonitor mate-system-monitor
setprogram appmenu appmenu
setprogram editor nvim-qt
setprogram termeditor nvim
setprogram lockscreen ilock
