#!/usr/bin/env bash
set -euo pipefail
APP_NAME="Govibe PC Specs"
APP_ID="govibepcspecs"
BIN_NAME="govibepcspecs"
DEPS="python3 python3-gobject gtk3 pciutils usbutils lshw dmidecode mesa-demos"
BASE_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
FILES_DIR="$BASE_DIR/files"
MODE="user"

case "${1:-}" in
  --system)
    MODE="system"
    ;;
  --install-deps)
    MODE="deps"
    ;;
  --print-deps)
    echo "$DEPS"
    exit 0
    ;;
  --help|-h)
    echo "Usage: ./install.sh [--system|--install-deps|--print-deps]"
    echo "Default: installs $APP_NAME for the desktop user, no sudo needed."
    echo "Safe even if you accidentally run: sudo ./install.sh"
    echo "System install: sudo ./install.sh --system"
    exit 0
    ;;
  "") ;;
  *)
    echo "Unknown option: $1" >&2
    echo "Run: ./install.sh --help" >&2
    exit 1
    ;;
esac

# Important Fedora fix:
# If the user accidentally runs sudo ./install.sh without --system,
# install into the real desktop user's home, not /root.
resolve_target_user() {
  if [ "$MODE" = "user" ] && [ "${EUID:-$(id -u)}" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "${SUDO_USER:-}" != "root" ]; then
    printf '%s\n' "$SUDO_USER"
  else
    id -un
  fi
}

resolve_home() {
  local user="$1"
  local home=""
  if command -v getent >/dev/null 2>&1; then
    home="$(getent passwd "$user" | awk -F: '{print $6}' || true)"
  fi
  if [ -z "$home" ]; then
    home="$(eval echo "~$user")"
  fi
  printf '%s\n' "$home"
}

TARGET_USER="$(resolve_target_user)"
TARGET_HOME="$(resolve_home "$TARGET_USER")"

run_root() {
  if [ "${EUID:-$(id -u)}" -eq 0 ]; then
    "$@"
  elif command -v sudo >/dev/null 2>&1; then
    sudo "$@"
  else
    echo "Root permission required for --system or --install-deps." >&2
    echo "Use ./install.sh for user install." >&2
    exit 1
  fi
}

maybe_chown_user_tree() {
  if [ "${EUID:-$(id -u)}" -eq 0 ] && [ "$TARGET_USER" != "root" ]; then
    chown -R "$TARGET_USER:$TARGET_USER" "$TARGET_HOME/.local/bin" "$TARGET_HOME/.local/share" "$TARGET_HOME/.local/lib" 2>/dev/null || true
  fi
}

install_deps() {
  if command -v dnf >/dev/null 2>&1; then
    run_root dnf install -y $DEPS || true
  elif command -v yum >/dev/null 2>&1; then
    run_root yum install -y $DEPS || true
  elif command -v apt >/dev/null 2>&1; then
    echo "This package targets Fedora, CentOS, and Red Hat style systems."
    echo "Install equivalent dependencies with apt if needed: $DEPS"
  else
    echo "No supported package manager found for automatic dependency install."
  fi
}

patch_user_files() {
  local bin_file="$TARGET_HOME/.local/bin/$BIN_NAME"
  if [ "$APP_ID" = "govibe-process-manager" ] && [ -f "$bin_file" ]; then
    cat > "$bin_file" <<'EOF_PM'
#!/bin/bash
export GDK_APPLICATION_ID=org.govibe.ProcessManager
exec -a govibe-process-manager python3 "$HOME/.local/share/govibe-process-manager/govibe_process_manager.py" "$@"
EOF_PM
    chmod 0755 "$bin_file"
  fi

  if [ "$APP_ID" = "govibepcspecs" ] && [ -f "$bin_file" ]; then
    python3 - "$bin_file" <<'PY_PATCH'
from pathlib import Path
import sys
p=Path(sys.argv[1])
s=p.read_text(errors='ignore')
s=s.replace('GVHWMEM_HELPER = "/usr/lib/govibepcspecs/gvhwmem"', 'GVHWMEM_HELPER = os.path.expanduser("~/.local/lib/govibepcspecs/gvhwmem")')
s=s.replace('GVHWGPU_HELPER = "/usr/lib/govibepcspecs/gvhwgpu"', 'GVHWGPU_HELPER = os.path.expanduser("~/.local/lib/govibepcspecs/gvhwgpu")')
p.write_text(s)
PY_PATCH
    chmod 0755 "$bin_file"
  fi

  if [ -d "$TARGET_HOME/.local/share/applications" ]; then
    find "$TARGET_HOME/.local/share/applications" -maxdepth 1 -type f \( -name "*$APP_ID*.desktop" -o -name "org.govibe.ProcessManager.desktop" \) | while read -r desktop; do
      case "$APP_ID" in
        govibe-nexus-audio-player)
          sed -i "s|^Exec=.*|Exec=$TARGET_HOME/.local/bin/govibe-nexus-audio-player %U|" "$desktop"
          ;;
        govibe-nexus-video-player)
          sed -i "s|^Exec=.*|Exec=$TARGET_HOME/.local/bin/govibe-nexus-video-player %U|" "$desktop"
          ;;
        govibepcspecs)
          sed -i "s|^Exec=.*|Exec=$TARGET_HOME/.local/bin/govibepcspecs|" "$desktop"
          ;;
        govibe-process-manager)
          sed -i "s|^Exec=.*|Exec=env GDK_APPLICATION_ID=org.govibe.ProcessManager BAMF_DESKTOP_FILE_HINT=$TARGET_HOME/.local/share/applications/org.govibe.ProcessManager.desktop $TARGET_HOME/.local/bin/govibe-process-manager --show|" "$desktop"
          ;;
      esac
    done
  fi
}

update_user_shell_path_hint() {
  local bashrc="$TARGET_HOME/.bashrc"
  if [ "$TARGET_USER" != "root" ] && [ -f "$bashrc" ]; then
    if ! grep -q 'HOME/.local/bin' "$bashrc" 2>/dev/null; then
      printf '\n# Govibe local apps\nexport PATH="$HOME/.local/bin:$PATH"\n' >> "$bashrc" || true
    fi
  fi
}

install_user() {
  mkdir -p "$TARGET_HOME/.local/bin" "$TARGET_HOME/.local/share" "$TARGET_HOME/.local/lib"
  [ -d "$FILES_DIR/usr/bin" ] && cp -a "$FILES_DIR/usr/bin/." "$TARGET_HOME/.local/bin/"
  [ -d "$FILES_DIR/usr/lib" ] && cp -a "$FILES_DIR/usr/lib/." "$TARGET_HOME/.local/lib/"
  if [ -d "$FILES_DIR/usr/share" ]; then
    cp -a "$FILES_DIR/usr/share/." "$TARGET_HOME/.local/share/"
  fi
  [ -f "$TARGET_HOME/.local/bin/$BIN_NAME" ] && chmod 0755 "$TARGET_HOME/.local/bin/$BIN_NAME"
  find "$TARGET_HOME/.local/lib/$APP_ID" -maxdepth 2 -type f 2>/dev/null | xargs -r chmod 0755 || true
  patch_user_files
  maybe_chown_user_tree
  update_user_shell_path_hint

  if [ "${EUID:-$(id -u)}" -eq 0 ] && [ "$TARGET_USER" != "root" ]; then
    su -s /bin/sh -c "command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database '$TARGET_HOME/.local/share/applications' >/dev/null 2>&1 || true" "$TARGET_USER" || true
    su -s /bin/sh -c "command -v gtk-update-icon-cache >/dev/null 2>&1 && [ -d '$TARGET_HOME/.local/share/icons/hicolor' ] && gtk-update-icon-cache -q -t -f '$TARGET_HOME/.local/share/icons/hicolor' >/dev/null 2>&1 || true" "$TARGET_USER" || true
  else
    if command -v update-desktop-database >/dev/null 2>&1; then
      update-desktop-database "$TARGET_HOME/.local/share/applications" >/dev/null 2>&1 || true
    fi
    if command -v gtk-update-icon-cache >/dev/null 2>&1 && [ -d "$TARGET_HOME/.local/share/icons/hicolor" ]; then
      gtk-update-icon-cache -q -t -f "$TARGET_HOME/.local/share/icons/hicolor" >/dev/null 2>&1 || true
    fi
  fi
}

install_system() {
  if [ ! -d "$FILES_DIR/usr" ]; then
    echo "Missing files/usr payload directory." >&2
    exit 1
  fi
  run_root cp -a "$FILES_DIR/usr/." /usr/
  [ -f "/usr/bin/$BIN_NAME" ] && run_root chmod 0755 "/usr/bin/$BIN_NAME"
  if [ "$APP_ID" = "govibepcspecs" ]; then
    run_root chown root:root /usr/lib/govibepcspecs/gvhwgpu /usr/lib/govibepcspecs/gvhwmem 2>/dev/null || true
    run_root chmod 4755 /usr/lib/govibepcspecs/gvhwgpu /usr/lib/govibepcspecs/gvhwmem 2>/dev/null || true
  fi
  if command -v update-desktop-database >/dev/null 2>&1; then
    run_root update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
  fi
  if command -v gtk-update-icon-cache >/dev/null 2>&1; then
    run_root gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
  fi
}

if [ "$MODE" = "deps" ]; then
  install_deps
  exit 0
fi

if [ ! -d "$FILES_DIR/usr" ]; then
  echo "Missing files/usr payload directory." >&2
  exit 1
fi

if [ "$MODE" = "system" ]; then
  echo "Installing $APP_NAME system-wide..."
  install_system
  echo "Installed system-wide: $APP_NAME"
else
  echo "Installing $APP_NAME for user: $TARGET_USER"
  echo "Target home: $TARGET_HOME"
  install_user
  echo "Installed for user: $APP_NAME"
  case ":${PATH:-}:" in
    *":$TARGET_HOME/.local/bin:"*) ;;
    *) echo "Note: run this now if terminal cannot find $BIN_NAME:"; echo "export PATH=\"$TARGET_HOME/.local/bin:\$PATH\"" ;;
  esac
fi

echo "Run with: $BIN_NAME"
