#!/bin/bash
# Wrapper script for pCloud
# This script:
# 1. Adds --no-sandbox flag (required for AppImage sandbox compatibility)
# 2. Handles desktop integration (installs .desktop file and icons)
# 3. Sanitizes inherited GUI launcher environment before Electron starts

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# GUI launches can inherit closed pipes from the parent app. Electron console
# writes then fail with EPIPE before the UI is usable.
if [ ! -t 1 ]; then
  exec 1>/dev/null
fi

if [ ! -t 2 ]; then
  exec 2>/dev/null
fi

sanitize_runtime_environment() {
  local CLEAN_LD_LIBRARY_PATH="${SCRIPT_DIR}/resources"
  local ENTRY
  local ENV_NAME
  local LD_LIBRARY_PATH_ENTRIES=()

  if [ -n "${LD_LIBRARY_PATH:-}" ]; then
    IFS=':' read -r -a LD_LIBRARY_PATH_ENTRIES <<< "${LD_LIBRARY_PATH}"
    for ENTRY in "${LD_LIBRARY_PATH_ENTRIES[@]}"; do
      if [ -z "${ENTRY}" ]; then
        continue
      fi

      case "${ENTRY}" in
        "${SCRIPT_DIR}"|"${SCRIPT_DIR}"/*)
          CLEAN_LD_LIBRARY_PATH="${CLEAN_LD_LIBRARY_PATH}:${ENTRY}"
          ;;
        *)
          if [ -n "${APPDIR:-}" ]; then
            case "${ENTRY}" in
              "${APPDIR}"|"${APPDIR}"/*)
                CLEAN_LD_LIBRARY_PATH="${CLEAN_LD_LIBRARY_PATH}:${ENTRY}"
                ;;
            esac
          fi
          ;;
      esac
    done
  fi

  export LD_LIBRARY_PATH="${CLEAN_LD_LIBRARY_PATH}"

  for ENV_NAME in $(compgen -v); do
    case "${ENV_NAME}" in
      MOZ_*|XRE_*)
        unset "${ENV_NAME}"
        ;;
    esac
  done
}

sanitize_runtime_environment

# Desktop integration function - installs .desktop file and icons for GNOME/KDE
# This ensures the correct icon appears in the dock/taskbar
integrate_desktop() {
  local APPIMAGE_PATH="${APPIMAGE:-$0}"
  local APP_NAME="pcloud"
  local DESKTOP_FILE_ID="appimagekit-${APP_NAME}"
  local DESKTOP_DIR="${HOME}/.local/share/applications"
  local ICON_DIR="${HOME}/.local/share/icons/hicolor"
  local DESKTOP_FILE="${DESKTOP_DIR}/${DESKTOP_FILE_ID}.desktop"
  local MARKER_FILE="${HOME}/.config/pcloud/.desktop-integrated"

  # Skip if already integrated (check marker file)
  if [ -f "${MARKER_FILE}" ]; then
    return 0
  fi

  # Create directories if they don't exist
  mkdir -p "${DESKTOP_DIR}" 2>/dev/null
  mkdir -p "${HOME}/.config/pcloud" 2>/dev/null

  # Create .desktop file
  cat > "${DESKTOP_FILE}" << DESKTOP_EOF
[Desktop Entry]
Name=pCloud
Comment=Secure cloud storage and file synchronization service
Exec="${APPIMAGE_PATH}" %U
Terminal=false
Type=Application
Icon=${DESKTOP_FILE_ID}
StartupWMClass=pcloud
StartupNotify=true
Categories=Network;FileTransfer;
Keywords=cloud;storage;sync;backup;files;
MimeType=x-scheme-handler/pcloud;
X-AppImage-Version=2.0.0
X-AppImage-Comment=Generated by pCloud AppImage
DESKTOP_EOF

  chmod +x "${DESKTOP_FILE}" 2>/dev/null

  # Install icons from the AppImage resources
  local ICON_SIZES="16x16 24x24 32x32 48x48 64x64 128x128 256x256 512x512"
  for SIZE in ${ICON_SIZES}; do
    local SRC_ICON="${SCRIPT_DIR}/resources/assets/icons/${SIZE}.png"
    local DEST_DIR="${ICON_DIR}/${SIZE}/apps"
    if [ -f "${SRC_ICON}" ]; then
      mkdir -p "${DEST_DIR}" 2>/dev/null
      cp "${SRC_ICON}" "${DEST_DIR}/${DESKTOP_FILE_ID}.png" 2>/dev/null
    fi
  done

  # Update icon cache (silently, don't fail if not available)
  if command -v gtk-update-icon-cache >/dev/null 2>&1; then
    gtk-update-icon-cache -f -t "${ICON_DIR}" 2>/dev/null || true
  fi

  # Update desktop database (silently, don't fail if not available)
  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "${DESKTOP_DIR}" 2>/dev/null || true
  fi

  # Create marker file to avoid re-integration on every launch
  touch "${MARKER_FILE}" 2>/dev/null

  echo "Desktop integration complete"
}

# Run desktop integration (silent, in background to not delay app startup)
integrate_desktop &

# Execute the real binary with --no-sandbox and pass through all arguments
exec "${SCRIPT_DIR}/pcloud.bin" --no-sandbox "$@"
