#!/usr/bin/env bash
# Shared Pi desktop / launcher setup for DyzineFrame.
# Used by install_script.sh (first-time) and update.sh (refresh).
#
#   bash ~/DyzineFrame/ensure_pi_desktop.sh
#
# Sets: autostart, wallpaper, script +x, harden_pi_desktop (WiFi/USB dialogs).

set -euo pipefail

if [[ "${EUID}" -eq 0 ]]; then
  echo "DO NOT RUN AS ROOT — run as topbox." >&2
  exit 1
fi

DF="${DYZINEFRAME_ROOT:-${HOME}/DyzineFrame}"
if [[ ! -d "${DF}" ]]; then
  echo "FATAL: missing ${DF}" >&2
  exit 1
fi

echo "=== ensure_pi_desktop (${DF}) ==="

mkdir -p "${HOME}/.config/autostart"
if [[ -f "${DF}/topboxboot.desktop" ]]; then
  cp -f "${DF}/topboxboot.desktop" "${HOME}/.config/autostart/topboxboot.desktop"
  echo "autostart: ${HOME}/.config/autostart/topboxboot.desktop"
else
  echo "WARN: missing ${DF}/topboxboot.desktop" >&2
fi

WALL="${DF}/Assets/Shared/1920x1080/POG_Render_02.png"
MODE_LINE="$(grep -E '^[[:space:]]*display_mode[[:space:]]*=' "${DF}/config.ini" 2>/dev/null | head -1 || true)"
MODE_VAL="$(printf '%s' "${MODE_LINE#*=}" | tr -d '[:space:]' | tr '[:lower:]' '[:upper:]')"
ASSET_LINE="$(grep -E '^[[:space:]]*asset_resolution[[:space:]]*=' "${DF}/config.ini" 2>/dev/null | head -1 || true)"
ASSET_VAL="$(printf '%s' "${ASSET_LINE#*=}" | tr -d '[:space:]')"
if [[ "${MODE_VAL}" == "STRIP" || "${MODE_VAL}" == "MINI" ]]; then
  if [[ -n "${ASSET_VAL}" && -f "${DF}/Assets/Shared/${ASSET_VAL}/pot_dyzine_logo.png" ]]; then
    WALL="${DF}/Assets/Shared/${ASSET_VAL}/pot_dyzine_logo.png"
  elif [[ -f "${DF}/Assets/Shared/1920x360/pot_dyzine_logo.png" ]]; then
    WALL="${DF}/Assets/Shared/1920x360/pot_dyzine_logo.png"
  fi
fi
if [[ -f "${WALL}" ]]; then
  if command -v pcmanfm >/dev/null 2>&1; then
    pcmanfm --set-wallpaper "${WALL}" 2>/dev/null || true
    echo "wallpaper: ${WALL}"
  else
    echo "WARN: pcmanfm not found — skip wallpaper" >&2
  fi
else
  echo "WARN: missing wallpaper ${WALL} (copy Assets/ on deploy)" >&2
fi

cd "${DF}"
chmod a+x \
  chknet.sh dis_pwrsve.sh dis_autoupdates.sh runit.sh run_supervisor.sh \
  cpu_affinity.sh set_cpu_affinity.sh \
  synctime.sh update.sh install_script.sh install.sh harden_pi_desktop.sh \
  ensure_pi_desktop.sh pi_python_policy.sh pi_hdmi_mode.py \
  2>/dev/null || true

# Persist HDMI mode for Mini strips (kanshi); apply when Wayland is up.
if [[ -f "${DF}/pi_hdmi_mode.py" ]]; then
  python3 "${DF}/pi_hdmi_mode.py" 2>/dev/null || true
fi

if [[ -f "${DF}/harden_pi_desktop.sh" ]]; then
  bash "${DF}/harden_pi_desktop.sh"
else
  echo "WARN: harden_pi_desktop.sh missing — skip dialog hardening" >&2
fi

echo "ensure_pi_desktop: done"
