#!/bin/bash

# AZERTY Global - Linux Installer
# Installs the XKB symbols, registers the layout and adds Compose rules.

set -e

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root (sudo ./install.sh)"
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LAYOUT_NAME="azerty_global"
SHORT_DESCRIPTION="azerty_global"
DESCRIPTION="French (AZERTY Global)"
SYMBOLS_SRC="$SCRIPT_DIR/azerty_global"
SYMBOLS_DEST="/usr/share/X11/xkb/symbols/$LAYOUT_NAME"
COMPOSE_SRC="$SCRIPT_DIR/.XCompose_azerty_global"

timestamp() {
    date +%Y%m%d_%H%M%S
}

backup_file() {
    local file="$1"
    local backup="${file}.backup.$(timestamp)"
    cp "$file" "$backup"
    echo "✓ Backed up $file to $backup"
}

register_layout() {
    local xml_file="$1"

    if [ ! -f "$xml_file" ]; then
        return
    fi

    if grep -q "<name>${LAYOUT_NAME}</name>" "$xml_file"; then
        echo "✓ Layout already registered in $xml_file"
        return
    fi

    backup_file "$xml_file"

    local tmp_file
    tmp_file="$(mktemp)"

    if awk \
        -v layout_name="$LAYOUT_NAME" \
        -v short_description="$SHORT_DESCRIPTION" \
        -v description="$DESCRIPTION" '
        function print_layout() {
            print "    <layout>"
            print "      <configItem>"
            print "        <name>" layout_name "</name>"
            print "        <shortDescription>" short_description "</shortDescription>"
            print "        <description>" description "</description>"
            print "        <languageList>"
            print "          <iso639Id>fra</iso639Id>"
            print "        </languageList>"
            print "      </configItem>"
            print "      <variantList/>"
            print "    </layout>"
        }
        /<\/layoutList>/ && inserted == 0 {
            print_layout()
            inserted = 1
        }
        { print }
        END {
            if (inserted == 0) {
                exit 1
            }
        }
    ' "$xml_file" > "$tmp_file"; then
        cp "$tmp_file" "$xml_file"
        rm -f "$tmp_file"
        echo "✓ Updated $xml_file"
    else
        rm -f "$tmp_file"
        echo "✗ Could not find </layoutList> in $xml_file" >&2
        exit 1
    fi
}

install_compose_rules() {
    echo ""
    echo "4. Installing Compose rules (for Dead Keys compliance)..."

    if [ ! -f "$COMPOSE_SRC" ]; then
        echo "✗ Missing Compose fragment: $COMPOSE_SRC" >&2
        exit 1
    fi

    local real_user
    local user_home
    local user_group
    local fragment_dest
    local compose_dest
    local include_line

    real_user=${SUDO_USER:-$USER}
    user_home=$(getent passwd "$real_user" | cut -d: -f6)
    user_group=$(id -gn "$real_user" 2>/dev/null || true)

    if [ -z "$user_group" ]; then
        user_group="$real_user"
    fi

    if [ -n "$user_home" ] && [ -d "$user_home" ]; then
        fragment_dest="$user_home/.XCompose_azerty_global"
        compose_dest="$user_home/.XCompose"
        include_line='include "%H/.XCompose_azerty_global"'

        install -m 0644 "$COMPOSE_SRC" "$fragment_dest"
        chown "$real_user:$user_group" "$fragment_dest"
        echo "✓ Installed AZERTY Global Compose fragment for user $real_user"

        if [ -f "$compose_dest" ]; then
            if grep -Fxq "$include_line" "$compose_dest"; then
                echo "✓ ~/.XCompose already includes AZERTY Global"
            else
                backup_file "$compose_dest"
                printf '\n%s\n' "$include_line" >> "$compose_dest"
                echo "✓ Added AZERTY Global include to existing ~/.XCompose"
            fi
        else
            printf 'include "%%L"\n%s\n' "$include_line" > "$compose_dest"
            echo "✓ Created ~/.XCompose with locale defaults and AZERTY Global include"
        fi

        chown "$real_user:$user_group" "$compose_dest"
    else
        echo "⚠ Could not detect real user home to install Compose rules"
        echo "  Please copy .XCompose_azerty_global to ~/.XCompose_azerty_global"
        echo "  Then add this line to ~/.XCompose:"
        echo '  include "%H/.XCompose_azerty_global"'
    fi
}

echo "Installing AZERTY Global..."

if [ ! -f "$SYMBOLS_SRC" ]; then
    echo "✗ Missing symbols file: $SYMBOLS_SRC" >&2
    exit 1
fi

# 1. Copy symbols file
install -m 0644 "$SYMBOLS_SRC" "$SYMBOLS_DEST"
echo "✓ Copied symbols file to $SYMBOLS_DEST"

# 2. Update XML rules (for GNOME, Wayland, KDE, etc.)
register_layout "/usr/share/X11/xkb/rules/evdev.xml"
register_layout "/usr/share/X11/xkb/rules/base.xml"

# 3. Install Compose rules
install_compose_rules

echo ""
echo "Success! Please restart your session (logout/login)."
echo "Then select 'French (AZERTY Global)' in your keyboard settings."
