#!/usr/bin/env bash
set -euo pipefail

SOURCE_DIR="/usr/local/share/kylin-cua"
REQUESTED_USER="${1:-}"

user_from_uid() {
    getent passwd "$1" | awk -F: 'NR == 1 { print $1 }'
}

is_regular_user() {
    local user="$1"
    local entry uid home shell uid_min
    entry="$(getent passwd "${user}" || true)"
    [[ -n "${entry}" ]] || return 1
    IFS=: read -r _ _ uid _ _ home shell <<<"${entry}"
    uid_min="$(awk '$1 == "UID_MIN" { print $2; exit }' /etc/login.defs 2>/dev/null || true)"
    uid_min="${uid_min:-1000}"
    [[ "${uid}" =~ ^[0-9]+$ ]] || return 1
    (( uid >= uid_min )) || return 1
    [[ "${home}" == /* && "${home}" != "/" ]] || return 1
    [[ "${shell}" != */nologin && "${shell}" != */false ]] || return 1
}

detect_target_user() {
    local candidate=""
    local -a regular_users=()

    if [[ -n "${KYLIN_CUA_TARGET_USER:-}" ]]; then
        printf '%s\n' "${KYLIN_CUA_TARGET_USER}"
        return 0
    fi
    if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" != "root" ]]; then
        printf '%s\n' "${SUDO_USER}"
        return 0
    fi
    if [[ -n "${PKEXEC_UID:-}" ]]; then
        candidate="$(user_from_uid "${PKEXEC_UID}")"
        if [[ -n "${candidate}" && "${candidate}" != "root" ]]; then
            printf '%s\n' "${candidate}"
            return 0
        fi
    fi
    if [[ -n "${SUDO_UID:-}" ]]; then
        candidate="$(user_from_uid "${SUDO_UID}")"
        if [[ -n "${candidate}" && "${candidate}" != "root" ]]; then
            printf '%s\n' "${candidate}"
            return 0
        fi
    fi

    while IFS= read -r candidate; do
        [[ -n "${candidate}" ]] || continue
        if is_regular_user "${candidate}"; then
            printf '%s\n' "${candidate}"
            return 0
        fi
    done < <(who 2>/dev/null | awk '{print $1}' | awk '!seen[$0]++')

    while IFS=: read -r candidate _ _ _ _ _ _; do
        if is_regular_user "${candidate}"; then
            regular_users+=("${candidate}")
        fi
    done < /etc/passwd
    if (( ${#regular_users[@]} == 1 )); then
        printf '%s\n' "${regular_users[0]}"
        return 0
    fi
    return 1
}

if [[ ! -d "${SOURCE_DIR}" ]]; then
    printf '[ERROR] Packaged source directory not found: %s\n' "${SOURCE_DIR}" >&2
    exit 1
fi

TARGET_USER="${REQUESTED_USER}"
if [[ -z "${TARGET_USER}" ]]; then
    TARGET_USER="$(detect_target_user || true)"
fi
if [[ -z "${TARGET_USER}" ]]; then
    printf '[WARN] Cannot determine the target desktop user.\n' >&2
    printf '[WARN] Run: sudo /usr/local/sbin/kylin-cua-install-user USERNAME\n' >&2
    exit 0
fi

PASSWD_ENTRY="$(getent passwd "${TARGET_USER}" || true)"
if [[ -z "${PASSWD_ENTRY}" ]]; then
    printf '[ERROR] User does not exist: %s\n' "${TARGET_USER}" >&2
    exit 1
fi
IFS=: read -r _ _ TARGET_UID TARGET_GID _ TARGET_HOME _ <<<"${PASSWD_ENTRY}"
if [[ "${TARGET_HOME}" != /* || "${TARGET_HOME}" == "/" ]]; then
    printf '[ERROR] Unsafe home directory for %s: %s\n' "${TARGET_USER}" "${TARGET_HOME}" >&2
    exit 1
fi

TARGET_DIR="${TARGET_HOME}/.local/share/kylin-cua"
install -d -m 0755 -o "${TARGET_UID}" -g "${TARGET_GID}"     "${TARGET_HOME}/.local" "${TARGET_HOME}/.local/share" "${TARGET_DIR}"
rsync -a --chown="${TARGET_UID}:${TARGET_GID}"     "${SOURCE_DIR}/" "${TARGET_DIR}/"

printf '[INFO] Installed Kylin CUA for %s at %s\n' "${TARGET_USER}" "${TARGET_DIR}"

SKILL_SOURCE_DIR="${SOURCE_DIR}/skill/kylin-cua"
if [[ -d "${SKILL_SOURCE_DIR}" ]]; then
    SKILL_DIRS=(
        "${TARGET_HOME}/.openclaw/skills"
        "${TARGET_HOME}/.hermes/skills"
        "${TARGET_HOME}/.kylin-agent-runtime/skills"
        "${TARGET_HOME}/.kylinbot/workspace/skills"
    )
    for SKILL_DIR in "${SKILL_DIRS[@]}"; do
        [[ -d "${SKILL_DIR}" ]] || continue
        SKILL_TARGET="${SKILL_DIR}/kylin-cua"
        rm -rf -- "${SKILL_TARGET}"
        rsync -a --chown="${TARGET_UID}:${TARGET_GID}"             "${SKILL_SOURCE_DIR}/" "${SKILL_TARGET}/"
        printf '[INFO] Installed Kylin CUA skill for %s at %s\n'             "${TARGET_USER}" "${SKILL_TARGET}"
    done
else
    printf '[WARN] Packaged skill directory not found: %s\n'         "${SKILL_SOURCE_DIR}" >&2
fi

YDOTOOL_INSTALLER="${SOURCE_DIR}/scripts/ydotool_install.sh"
printf '[INFO] Installing ydotool for %s with %s\n'     "${TARGET_USER}" "${YDOTOOL_INSTALLER}"
bash "${YDOTOOL_INSTALLER}"     "${SOURCE_DIR}/vendor/ydotool" "${TARGET_USER}"
