#!/bin/bash
# Step 05: Boot splash (Plymouth) and desktop wallpaper

step_05_splash_wallpaper() {
  mkdir -p "$PLYMOUTH_DIR" /usr/share/rpd-wallpaper

  if ! curl -fsSL "${FILE_SERVER}/splash.png" -o "$PLYMOUTH_DIR/splash.png"; then
    log "WARNING: Could not download splash.png"; return 0
  fi
  cp "$PLYMOUTH_DIR/splash.png" "$WALLPAPER_PATH"
  chmod 644 "$PLYMOUTH_DIR/splash.png" "$WALLPAPER_PATH"

  # Plymouth theme
  if curl -fsSL "${FILE_SERVER}/custom.plymouth" -o "$PLYMOUTH_DIR/custom.plymouth" \
     && curl -fsSL "${FILE_SERVER}/custom.script" -o "$PLYMOUTH_DIR/custom.script"; then
    chmod 644 "$PLYMOUTH_DIR/custom.plymouth" "$PLYMOUTH_DIR/custom.script"
    log "Plymouth theme installed"
  fi
  grep -q '^Theme=custom' /etc/plymouth/plymouthd.conf 2>/dev/null \
    || printf '%s\n' '[Daemon]' 'Theme=custom' >> /etc/plymouth/plymouthd.conf
  log "Running update-initramfs ..."
  update-initramfs -u -k all 2>/dev/null || true

  # LightDM wallpaper
  mkdir -p /etc/lightdm/lightdm.conf.d
  curl -fsSL "${FILE_SERVER}/99-wallpaper.conf" -o /etc/lightdm/lightdm.conf.d/99-wallpaper.conf 2>/dev/null || true

  # Desktop wallpaper (pcmanfm)
  for PROFILE in LXDE-pi default; do
    local conf="$PI_HOME/.config/pcmanfm/$PROFILE/desktop-items-0.conf"
    mkdir -p "$(dirname "$conf")"
    if [[ ! -f "$conf" ]]; then
      printf '%s\n' '[*]' "wallpaper=$WALLPAPER_PATH" "wallpaper_mode=$WALLPAPER_MODE" 'wallpaper_common=1' 'show_trash=0' > "$conf"
    else
      grep -q '^wallpaper=' "$conf" && sed -i "s|^wallpaper=.*|wallpaper=$WALLPAPER_PATH|" "$conf" || echo "wallpaper=$WALLPAPER_PATH" >> "$conf"
      grep -q '^wallpaper_mode=' "$conf" && sed -i "s/^wallpaper_mode=.*/wallpaper_mode=$WALLPAPER_MODE/" "$conf" || echo "wallpaper_mode=$WALLPAPER_MODE" >> "$conf"
      grep -q '^show_trash=' "$conf" && sed -i 's/^show_trash=.*/show_trash=0/' "$conf" || echo 'show_trash=0' >> "$conf"
    fi
    chown -R "$PI_USER:$PI_USER" "$(dirname "$conf")"
  done

  # Taskbar start-here icon
  if curl -fsSL "${FILE_SERVER}/start-here.png" -o /tmp/start-here.png 2>/dev/null; then
    local icons="/usr/share/icons/PiXtrix"
    if [[ -d "$icons/32x32/places" ]]; then
      for s in 16 24 32 48 64 96; do
        local dest="$icons/${s}x${s}/places/start-here.png"
        [[ -d "$(dirname "$dest")" ]] || continue
        rm -f "$dest"
        if command -v convert >/dev/null 2>&1; then
          convert /tmp/start-here.png -resize "${s}x${s}" "$dest" 2>/dev/null || cp /tmp/start-here.png "$dest"
        else
          cp /tmp/start-here.png "$dest"
        fi
        chmod 644 "$dest"
      done
      log "Taskbar start-here icon installed"
    fi
    rm -f /tmp/start-here.png
  fi

  log "Splash and wallpaper configured"
}
