#!/bin/bash
# Step 04: Download kiosk scripts and launcher files from file server

step_04_kiosk_files() {
  mkdir -p "$AUTOSTART" "$PI_HOME/Desktop" "$PI_HOME/.local/share/applications"

  # Extension: disable text selection so touch-drag scrolls
  EXT_DIR="$PI_HOME/.local/share/chromium-kiosk-no-select"
  mkdir -p "$EXT_DIR"
  if curl -fsSL "${FILE_SERVER}/chromium-kiosk-no-select/manifest.json" -o "$EXT_DIR/manifest.json" 2>/dev/null && \
     curl -fsSL "${FILE_SERVER}/chromium-kiosk-no-select/no-select.css" -o "$EXT_DIR/no-select.css" 2>/dev/null && \
     curl -fsSL "${FILE_SERVER}/chromium-kiosk-no-select/inject.js" -o "$EXT_DIR/inject.js" 2>/dev/null; then
    chown -R "$PI_USER:$PI_USER" "$EXT_DIR"
    log "Chromium kiosk no-select extension installed"
  fi

  curl -fsSL "${FILE_SERVER}/start-chromium.sh" -o "$PI_HOME/start-chromium.sh"
  curl -fsSL "${FILE_SERVER}/chromium-kiosk.desktop" -o "$AUTOSTART/chromium-kiosk.desktop"
  chmod 755 "$PI_HOME/start-chromium.sh"
  chmod 644 "$AUTOSTART/chromium-kiosk.desktop"
  chown "$PI_USER:$PI_USER" "$PI_HOME/start-chromium.sh" "$AUTOSTART/chromium-kiosk.desktop"

  # Desktop launcher icon
  if curl -fsSL "${FILE_SERVER}/chromium-kiosk-launcher.desktop" -o /tmp/chromium-kiosk-launcher.desktop 2>/dev/null; then
    sed "s|/home/pi|$PI_HOME|g" /tmp/chromium-kiosk-launcher.desktop > "$PI_HOME/Desktop/Chromium Kiosk.desktop"
    sed "s|/home/pi|$PI_HOME|g" /tmp/chromium-kiosk-launcher.desktop > "$PI_HOME/.local/share/applications/chromium-kiosk-launcher.desktop"
    chmod 755 "$PI_HOME/Desktop/Chromium Kiosk.desktop"
    chmod 644 "$PI_HOME/.local/share/applications/chromium-kiosk-launcher.desktop"
    chown "$PI_USER:$PI_USER" "$PI_HOME/Desktop/Chromium Kiosk.desktop" "$PI_HOME/.local/share/applications/chromium-kiosk-launcher.desktop"
    # Mark as trusted so pcmanfm shows the icon instead of a text file
    sudo -u "$PI_USER" gio set "$PI_HOME/Desktop/Chromium Kiosk.desktop" metadata::trusted true 2>/dev/null || true
    rm -f /tmp/chromium-kiosk-launcher.desktop
    log "Chromium kiosk launcher installed"
  fi

  # 5-tap close Chromium overlay
  if curl -fsSL "${FILE_SERVER}/five-tap-close-chromium.py" -o "$PI_HOME/five-tap-close-chromium.py" 2>/dev/null; then
    chmod 755 "$PI_HOME/five-tap-close-chromium.py"
    if curl -fsSL "${FILE_SERVER}/five-tap-close-chromium.desktop" -o "$AUTOSTART/five-tap-close-chromium.desktop" 2>/dev/null; then
      sed -i "s|/home/pi|$PI_HOME|g" "$AUTOSTART/five-tap-close-chromium.desktop"
      chmod 644 "$AUTOSTART/five-tap-close-chromium.desktop"
      chown "$PI_USER:$PI_USER" "$PI_HOME/five-tap-close-chromium.py" "$AUTOSTART/five-tap-close-chromium.desktop"
      log "5-tap close Chromium installed"
    fi
  fi

  log "Kiosk files installed"
}
