#!/bin/bash
# Step 06: LightDM session config + DSI panel wait service

step_06_lightdm() {
  mkdir -p /etc/lightdm/lightdm.conf.d

  curl -fsSL "${FILE_SERVER}/99-default-session.conf" \
    -o /etc/lightdm/lightdm.conf.d/99-default-session.conf 2>/dev/null || true

  if [[ -f /etc/lightdm/lightdm.conf ]]; then
    sed -i "s/^user-session=.*/user-session=$LIGHTDM_SESSION/" /etc/lightdm/lightdm.conf
    sed -i "s/^autologin-session=.*/autologin-session=$LIGHTDM_SESSION/" /etc/lightdm/lightdm.conf
    log "LightDM session set to $LIGHTDM_SESSION"
  fi

  # Wait for DSI panel to report "connected" before LightDM starts (max 30s)
  mkdir -p /etc/systemd/system/lightdm.service.d
  cat > /etc/systemd/system/cm4-await-display.service << 'AWAITSVC'
[Unit]
Description=Wait for reTerminal DM DSI panel before LightDM
Before=lightdm.service
DefaultDependencies=no

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/sh -c 'echo "Waiting for DSI panel..."; for i in $(seq 1 30); do for f in /sys/class/drm/card*-DSI-1/status; do [ -f "$f" ] && [ "$(cat "$f" 2>/dev/null)" = "connected" ] && echo "DSI connected." && exit 0; done; sleep 1; done; echo "DSI timeout (30s), starting anyway."'
TimeoutStartSec=35

[Install]
WantedBy=graphical.target
AWAITSVC

  printf '%s\n' '[Unit]' 'After=cm4-await-display.service' \
    > /etc/systemd/system/lightdm.service.d/99-await-display.conf
  systemctl daemon-reload
  systemctl enable cm4-await-display.service 2>/dev/null || true
  log "cm4-await-display.service installed (wait for DSI, max 30s)"

  # Enable VNC (wayvnc) for remote access
  if command -v raspi-config >/dev/null 2>&1; then
    raspi-config nonint do_vnc 0
    log "VNC (wayvnc) enabled on port 5900"
  else
    log "WARNING: raspi-config not found, skipping VNC setup"
  fi

}
