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

MARK_DIR="${XDG_CONFIG_HOME:-${HOME}/.config}/saikyo-os"
MARK_FILE="${MARK_DIR}/first-login-kde.done"
WALLPAPER_PATH="/usr/share/wallpapers/Saikyo/contents/images/saikyo-default.svg"
LOGO_PATH="/usr/share/saikyo-os/logos/saikyo-logo.svg"
AVATAR_PNG="/usr/share/icons/hicolor/512x512/apps/distributor-logo.png"
COLOR_SCHEME="SaikyoDark"

mkdir -p "${MARK_DIR}" 2>/dev/null || true

if [[ -f "${MARK_FILE}" ]]; then
  exit 0
fi

if [[ ! -r "${WALLPAPER_PATH}" ]]; then
  exit 0
fi

have_cmd() { command -v "$1" >/dev/null 2>&1; }

apply_look_and_feel() {
  if have_cmd lookandfeeltool; then
    lookandfeeltool -a org.saikyo.desktop >/dev/null 2>&1 || true
  elif have_cmd lookandfeeltool5; then
    lookandfeeltool5 -a org.saikyo.desktop >/dev/null 2>&1 || true
  fi
}

apply_color_scheme() {
  if have_cmd plasma-apply-colorscheme; then
    plasma-apply-colorscheme "${COLOR_SCHEME}" >/dev/null 2>&1 || true
  fi

  if have_cmd kwriteconfig5; then
    kwriteconfig5 --file kdeglobals --group General --key ColorScheme "${COLOR_SCHEME}" >/dev/null 2>&1 || true
  elif have_cmd kwriteconfig6; then
    kwriteconfig6 --file kdeglobals --group General --key ColorScheme "${COLOR_SCHEME}" >/dev/null 2>&1 || true
  fi
}

restart_plasma_shell() {
  if have_cmd kquitapp5 && have_cmd kstart5; then
    kquitapp5 plasmashell >/dev/null 2>&1 || true
    nohup kstart5 plasmashell >/dev/null 2>&1 &
  elif have_cmd kquitapp6 && have_cmd kstart6; then
    kquitapp6 plasmashell >/dev/null 2>&1 || true
    nohup kstart6 plasmashell >/dev/null 2>&1 &
  fi
}

set_wallpaper() {
  local qdbus_cmd="$1"
  "${qdbus_cmd}" org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.evaluateScript "
    var Desktops = desktops();
    for (i = 0; i < Desktops.length; i++) {
      d = Desktops[i];
      d.wallpaperPlugin = 'org.kde.image';
      d.currentConfigGroup = ['Wallpaper', 'org.kde.image', 'General'];
      d.writeConfig('Image', 'file://${WALLPAPER_PATH}');
    }
  " >/dev/null 2>&1 || return 1
  return 0
}

if have_cmd qdbus; then
  set_wallpaper qdbus || true
elif have_cmd qdbus6; then
  set_wallpaper qdbus6 || true
fi

apply_color_scheme
apply_look_and_feel
restart_plasma_shell || true

add_panel_widgets_and_pins() {
  local qdbus_cmd="$1"
  "${qdbus_cmd}" org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.evaluateScript "
    function firstPanel() {
      var ps = panels();
      if (!ps || ps.length === 0) return null;
      return ps[0];
    }

    function ensureWidget(panel, pluginId) {
      try {
        var ws = panel.widgets();
        for (var i = 0; i < ws.length; i++) {
          if (ws[i].type === pluginId) return;
        }
        panel.addWidget(pluginId);
      } catch (e) {
      }
    }

    function ensureTaskManagerPins(panel, launchersStr) {
      try {
        var ws = panel.widgets();
        for (var i = 0; i < ws.length; i++) {
          if (ws[i].type === 'org.kde.plasma.taskmanager') {
            var tm = ws[i];
            tm.currentConfigGroup = ['General'];
            tm.writeConfig('launchers', launchersStr);
            return;
          }
        }
      } catch (e) {
      }
    }

    var p = firstPanel();
    if (!p) return;

    // License status widget
    ensureWidget(p, 'org.saikyo.license');

    // Pinned launchers in task manager
    var launchers = [
      'applications:org.kde.discover.desktop',
      'applications:systemsettings.desktop',
      'applications:saikyo-license.desktop'
    ].join(',');
    ensureTaskManagerPins(p, launchers);
  " >/dev/null 2>&1 || true
}

if have_cmd qdbus; then
  add_panel_widgets_and_pins qdbus || true
elif have_cmd qdbus6; then
  add_panel_widgets_and_pins qdbus6 || true
fi

desktop_dir="${HOME}/Desktop"
if [[ -r "${HOME}/.config/user-dirs.dirs" ]]; then
  d=$(grep -E '^XDG_DESKTOP_DIR=' "${HOME}/.config/user-dirs.dirs" | head -n 1 | cut -d= -f2- | tr -d '"')
  d=${d//\$HOME/${HOME}}
  if [[ -n "${d}" ]]; then desktop_dir="${d}"; fi
fi

# Ensure KWallet doesn't require a pre-existing GPG key by default.
# This prevents first-run failures in apps that request KWallet integration.
mkdir -p "${XDG_CONFIG_HOME:-${HOME}/.config}" 2>/dev/null || true
{
  echo "[Wallet]"
  echo "UseGpg=false"
} > "${XDG_CONFIG_HOME:-${HOME}/.config}/kwalletrc" 2>/dev/null || true

# Set a default user avatar for new sessions (shown in KDE menus/panel).
# Prefer PNG (KDE reliably picks it up); fallback to SVG.
if [[ -r "${AVATAR_PNG}" ]]; then
  cp -f "${AVATAR_PNG}" "${HOME}/.face.icon" 2>/dev/null || true
  chmod 0644 "${HOME}/.face.icon" 2>/dev/null || true
elif [[ -r "${LOGO_PATH}" ]]; then
  cp -f "${LOGO_PATH}" "${HOME}/.face.icon" 2>/dev/null || true
  chmod 0644 "${HOME}/.face.icon" 2>/dev/null || true
fi

mkdir -p "${desktop_dir}" 2>/dev/null || true
if [[ -r /usr/share/applications/saikyo-license.desktop ]]; then
  cp -f /usr/share/applications/saikyo-license.desktop "${desktop_dir}/SAIKYO OS License.desktop" 2>/dev/null || true
  chmod 0755 "${desktop_dir}/SAIKYO OS License.desktop" 2>/dev/null || true
fi

if [[ -r /usr/share/applications/org.kde.discover.desktop ]]; then
  cp -f /usr/share/applications/org.kde.discover.desktop "${desktop_dir}/SAIKYO Discover.desktop" 2>/dev/null || true
  chmod 0755 "${desktop_dir}/SAIKYO Discover.desktop" 2>/dev/null || true
fi

if [[ -r /usr/share/applications/systemsettings.desktop ]]; then
  cp -f /usr/share/applications/systemsettings.desktop "${desktop_dir}/System Settings.desktop" 2>/dev/null || true
  chmod 0755 "${desktop_dir}/System Settings.desktop" 2>/dev/null || true
fi

if have_cmd kdialog; then
  msg="Добро пожаловать в SAIKYO OS.\n\nНа этой системе действует пробный период 7 дней.\nПосле истечения пробного периода потребуется полная активация лицензии.\n\nРекомендуется выполнить активацию заранее."
  if kdialog --title "SAIKYO OS" --icon "${LOGO_PATH}" --yes-label "Открыть активацию" --no-label "Позже" --yesno "${msg}" 2>/dev/null; then
    if have_cmd saikyo-license-kde; then
      nohup saikyo-license-kde >/dev/null 2>&1 &
    fi
  fi
fi

touch "${MARK_FILE}" 2>/dev/null || true
exit 0
