#!/bin/bash
# Step 11: Install one-shot and per-login scripts

step_11_oneshots() {
  # Rotation: pre-create kanshi config so it's ready before the desktop session starts,
  # then install set-rotation-at-login to re-apply on every login.
  if [[ -n "$DSI_ROTATE" ]]; then
    log "Rotation $DSI_ROTATE set via cmdline"
    local kanshi_dir="$PI_HOME/.config/kanshi"
    mkdir -p "$kanshi_dir"
    cat > "$kanshi_dir/config" <<KANSHI
profile {
	output DSI-1 enable scale 1.000000 mode 800x1280@60.000 position 0,0 transform $DSI_ROTATE
}
KANSHI
    chown -R "$PI_USER:$PI_USER" "$kanshi_dir"
    log "Pre-created kanshi config (transform $DSI_ROTATE)"
    if curl -fsSL "${FILE_SERVER}/set-rotation-at-login.sh" -o "$PI_HOME/set-rotation-at-login.sh" 2>/dev/null; then
      chmod 755 "$PI_HOME/set-rotation-at-login.sh"
      chown "$PI_USER:$PI_USER" "$PI_HOME/set-rotation-at-login.sh"
      if curl -fsSL "${FILE_SERVER}/set-rotation-at-login.desktop" -o /tmp/sral.desktop 2>/dev/null; then
        sed "s|/home/pi|$PI_HOME|g" /tmp/sral.desktop > "$AUTOSTART/set-rotation-at-login.desktop"
        chown "$PI_USER:$PI_USER" "$AUTOSTART/set-rotation-at-login.desktop"
        rm -f /tmp/sral.desktop
        log "set-rotation-at-login installed"
      fi
    fi
  fi

  # Additional one-shots from config
  if [[ -n "$ONESHOT_SCRIPTS" ]]; then
    for _name in $ONESHOT_SCRIPTS; do
      install_oneshot "$_name" || true
    done
  else
    log "No additional one-shot scripts"
  fi
}
