#!/bin/bash

exec >"$(basename $0)".log 2>&1

cp ${srcdir}/../data/kbd-model-map scratch
chmod u+w scratch/kbd-model-map
rm -f scratch/keyboard
rm -f scratch/xkeyboard
. ${srcdir}/ref-dbus.sh
. ${srcdir}/ref-polkit.sh
gdbus call \
      --system \
      --dest org.freedesktop.locale1 \
      --object-path /org/freedesktop/locale1 \
      --method org.freedesktop.locale1.SetX11Keyboard \
      "'fr'" "''" "'latin9'" "''" true true
cmp scratch/xkeyboard << EOF
# Automatically generated by blocaled
# Minimal xorg.xonf for keyboard layout

Section "InputClass"
        Identifier "Blocaled Keyboard"
        MatchIsKeyboard "on"
        Option "XkbLayout" "fr"
        Option "XkbVariant" "latin9"
EndSection
EOF
RES=$?

if [ $RES = 0 ]; then
    echo PASS: write-X11
    cmp scratch/keyboard <<- EOF
	KEYMAP='fr-latin9'
	EOF
RES=$?
fi

if [ $RES = 0 ]; then
    echo PASS: convert
    ls -l scratch/xkeyboard >scratch/error
    sed -i 's/ .*//' scratch/error
    cmp scratch/error << EOF
-rw-r--r--
EOF
RES=$?
fi

if [ $RES = 0 ]; then
    echo PASS: permissions
    LANG=C gdbus call \
      --system \
      --dest org.freedesktop.locale1 \
      --object-path /org/freedesktop/locale1 \
      --method org.freedesktop.locale1.SetX11Keyboard \
      "'de'" "''" "'euro2'" "''" false false |& cmp ${srcdir}/scratch/keyboard-write-result1
    RES=$?
fi
if [ $RES = 0 ]; then
    echo PASS: X11 Not authorized
    rm scratch/keyboard
    rm scratch/xkeyboard
    . ${srcdir}/unref-localed.sh
    sleep 0.1
    . ${srcdir}/ref-localed.sh --foreground 2>scratch/error
    gdbus call \
      --system \
      --dest org.freedesktop.locale1 \
      --object-path /org/freedesktop/locale1 \
      --method org.freedesktop.locale1.SetX11Keyboard \
      "'oh'" "''" "''" "''" true true
    sleep 0.1
    cmp scratch/error << EOF
Failed to find conversion entry for x11 layout 'oh' in '$(pwd)/scratch/kbd-model-map'
EOF
    RES=$?
fi
if [ $RES = 0 ]; then
    rm -f scratch/keyboard
    rm -f scratch/xkeyboard
    rm -f scratch/error
fi
rm scratch/kbd-model-map
. ${srcdir}/unref-localed.sh
. ${srcdir}/unref-polkit.sh
. ${srcdir}/unref-dbus.sh
exit $RES
