#!/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"
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 \
  2>/dev/null || true

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"
