#!/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=">>h Keyboard layouts
$(cat layouts)
:gadd layout
:rclose menu"
    CHOICE=$(echo "$LIST" | sed 's/^$/>/g' | instantmenu -c -w -1 -l 40 -q 'search' -p 'keyboard layout manager' -bw 4)
    [ -z "$CHOICE" ] && exit
    if grep "^$CHOICE$" layouts; then
        LAYOUTCHOICE="$(echo ">>h $CHOICE
:r Delete
:b Back" | instantmenu -c -l 20 -h -1 -bw 4 -q "layout options: $CHOICE")"

        # todo feaures
        #:b Move up
        #:b 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 -bw 4 -q 'add layout' -c -l 40)"
        if [ -n "$ADDEDLAYOUT" ]; then
            echo "adding layout"
            echo "$ADDEDLAYOUT" >>layouts
        fi
        ;;
    esac
done
