#!/bin/bash

# keyboard layout switcher
# and list editor

if [ -z "$1" ]; then
    echo "no options"
    exit
fi

mkdir -p ~/.config/instantos/
cd ~/.config/instantos/ || exit 1
if [ -e ./layouts ] && grep -q .. ./layouts; then
    echo "layouts found"
else
    ./layouts
    echo "inititalizing layouts"
    if ! iconf layout; then
        iconf layout us
    fi
    iconf layout >layouts

fi

# convert layout selection to applet
if [ "$1" = "apply" ]; then
    pgrep gxkb && RESTARTAPPLET=true
    if [ -e ~/.config/gxkb/gxkb.cfg ] && grep '^layout' ~/.config/gxkb/gxkb.cfg; then
        echo "gxkb config found"
    else
        echo "initiating gxkb config"
        pgrep gxkb || gxkb &
        for i in {1..15}; do
            echo "waiting for config: $i"
            sleep 2
            if [ -e ~/.config/gxkb/gxkb.cfg ]; then
                pkill gxkb
                break
            fi
        done
    fi

    echo "applying layouts to gxkb"
    LAYOUTS="$(tr '\n' ',' <~/.config/instantos/layouts | grep -o '.*[^,]')"
    echo "setting layouts to $LAYOUTS"

    if [ -n "$RESTARTAPPLET" ]; then
        echo "restartring gxkb"
        pkill gxkb
        sleep 2
        gxkb &
    fi

    exit
fi

# layout list editor
while :; do
    LIST="{heading} Keyboard layouts
$(cat layouts)
{green} add layout
{red} close menu"
    CHOICE=$(echo "$LIST" | grep '.' | instantmenu \
        --position center \
        --width auto \
        --lines 40 \
        --placeholder 'search' \
        --prompt 'keyboard layout manager' \
        --border-width 4)
    [ -z "$CHOICE" ] && exit
    if grep "^$CHOICE$" layouts; then
        LAYOUTCHOICE="$(echo "{heading} $CHOICE
{red icon=trash} Delete
{blue icon=arrow-left} Back" | instantmenu \
            --position center \
            --lines 20 \
            --line-height auto \
            --border-width 4 \
            --placeholder "layout options: $CHOICE")"

        # todo feaures
        # {blue icon=chevron-up} Move up
        # {blue icon=chevron-down} Move down

        case "$LAYOUTCHOICE" in
            *Delete)
                echo "deleting $CHOICE"
                sed -i "/^$CHOICE$/d" layouts
                ;;
            *Back)
                echo "going back"
                ;;
        esac
    fi

    case "$CHOICE" in
        *menu)
            exit
            ;;
        *layout)
            echo "adding layouts"
            ADDEDLAYOUT="$(localectl list-x11-keymap-layouts | instantmenu \
                --border-width 4 \
                --placeholder 'add layout' \
                --position center \
                --lines 40)"
            if [ -n "$ADDEDLAYOUT" ]; then
                echo "adding layout"
                echo "$ADDEDLAYOUT" >>layouts
            fi
            ;;
    esac
done
