#!/bin/bash

set -euo pipefail

readonly CLIM_ROOT="/opt/Clim"
readonly CLIM_DIR="${CLIM_ROOT}/clim"
readonly START_SCRIPT="/usr/local/bin/start-clim"
readonly STOP_SCRIPT="/usr/local/bin/stop-clim"
readonly REPAIR_LOG="${CLIM_ROOT}/clim-system-repair.log"
readonly AUTOSTART_DIR="/etc/xdg/autostart"
readonly DESKTOP_FILE="${AUTOSTART_DIR}/clim.desktop"
readonly APPLICATIONS_DIR="/usr/share/applications"
readonly ICON_PATH="${CLIM_ROOT}/service/icon.png"

log() {
    local ts
    ts="$(date '+%Y-%m-%d %H:%M:%S')"
    mkdir -p "${CLIM_ROOT}" 2>/dev/null || true
    echo "[${ts}] $1" >> "${REPAIR_LOG}" 2>/dev/null || true
}

require_root() {
    if [[ "${EUID}" -ne 0 ]]; then
        log "ОШИБКА: скрипт должен запускаться от root"
        exit 1
    fi
}

ensure_exec() {
    local file="$1"
    if [[ -f "${file}" ]]; then
        chmod 755 "${file}" 2>/dev/null || true
    fi
}

ensure_dir_rw_for_all() {
    local dir="$1"
    if [[ -d "${dir}" ]]; then
        chmod 777 "${dir}" 2>/dev/null || true
    fi
}

ensure_autostart_desktop() {
    if [[ ! -x "${START_SCRIPT}" ]]; then
        log "Пропуск создания clim.desktop: не найден ${START_SCRIPT}"
        return 0
    fi

    mkdir -p "${AUTOSTART_DIR}" 2>/dev/null || true
    cat > "${DESKTOP_FILE}" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=Evolenta-CLIM
Name[ru]=Evolenta-CLIM
Comment=CLIM startup script
Exec=/usr/local/bin/start-clim
StartupNotify=false
Terminal=false
Icon=${ICON_PATH}
Categories=Utility;
EOF
    chmod 755 "${DESKTOP_FILE}" 2>/dev/null || true
    if [[ -d "${APPLICATIONS_DIR}" ]]; then
        cp -f "${DESKTOP_FILE}" "${APPLICATIONS_DIR}/clim.desktop" 2>/dev/null || true
        chmod 755 "${APPLICATIONS_DIR}/clim.desktop" 2>/dev/null || true
    fi
}

main() {
    require_root
    log "Старт проверки после загрузки системы"

    if [[ ! -d "${CLIM_ROOT}" ]]; then
        log "Пропуск: директория ${CLIM_ROOT} не найдена"
        exit 0
    fi

    ensure_exec "${START_SCRIPT}"
    ensure_exec "${STOP_SCRIPT}"
    ensure_exec "${CLIM_DIR}/clim"
    ensure_exec "/usr/local/bin/clim-session-cleanup"
    ensure_exec "/usr/local/bin/clim-remove-stale-lock"

    ensure_dir_rw_for_all "${CLIM_DIR}/logs"
    ensure_dir_rw_for_all "${CLIM_DIR}/Logs"
    find "${CLIM_DIR}/logs" "${CLIM_DIR}/Logs" -type d -exec chmod 777 {} \; 2>/dev/null || true
    find "${CLIM_DIR}/logs" "${CLIM_DIR}/Logs" -type f -exec chmod 666 {} \; 2>/dev/null || true

    if [[ -x "${CLIM_DIR}/magick" ]]; then
        ln -sf "${CLIM_DIR}/magick" "${CLIM_DIR}/convert" 2>/dev/null || true
    fi

    ensure_autostart_desktop
    log "Проверка завершена успешно"
}

main "$@"
