#!/bin/sh

if [ "$(whoami)" = "root" ]; then
    echo "Will not run as root."
    echo "You should run this setup script as the desktop user."
    exit 1
fi

LOCAL_SHARE="${XDG_DATA_HOME:-$HOME/.local/share}"

mkdir -p "$LOCAL_SHARE/hawck/scripts"
mkdir -p "$LOCAL_SHARE/hawck/scripts-enabled"

## Install example script if it does not exist.
## The user may rewrite this script without renaming it, so the check
## is critical.
if ! [ -f "$LOCAL_SHARE/hawck/scripts/example.hwk" ]; then
    install -m 644 -D /usr/share/hawck/scripts/example.hwk "$LOCAL_SHARE/hawck/scripts/example.hwk"
fi
if ! [ -f "$LOCAL_SHARE/hawck/cfg.lua" ]; then
    install -m 644 -D /usr/share/hawck/cfg.lua "$LOCAL_SHARE/hawck/cfg.lua"
fi

LLIB="$LOCAL_SHARE/hawck/scripts/LLib"
[ -e "$LLIB" ] || ln -s /usr/share/hawck/LLib "$LLIB"
KEYMAPS_LNK="$LOCAL_SHARE/hawck/scripts/keymaps"
[ -e "$KEYMAPS_LNK" ] || ln -s /usr/share/hawck/keymaps "$KEYMAPS_LNK"
INIT_LNK="$LOCAL_SHARE/hawck/scripts/init.lua"
[ -e "$INIT_LNK" ] || ln -s /usr/share/hawck/LLib/init.lua "$INIT_LNK"


INPUT_SHARE_GRP=hawck-input-share
if ! groups | tr " " "\n" | grep "^$INPUT_SHARE_GRP\$" > /dev/null; then
    SBIN_USERMOD=/usr/sbin/usermod
    USERMOD=usermod
    if ! command -v "$USERMOD"; then
        if [ -f "$SBIN_USERMOD" ]; then
            USERMOD="$SBIN_USERMOD"
        else
            echo "Unable to locate usermod."
            echo "You need to add your user to the $INPUT_SHARE_GRP group."
            exit 1
        fi
    fi
    sudo "$USERMOD" -aG "$INPUT_SHARE_GRP" "$(whoami)"
fi
