#!/usr/bin/env bash
# WakeDesk universal Linux installer
# Supports: Raspberry Pi OS, Debian, Ubuntu, Kali Linux (and any Debian-based distro)
# Architectures: arm64 / aarch64 (Raspberry Pi 4/5), amd64 / x86_64 (Intel/AMD)
# Usage: bash install_wakedesk.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# ── Colours ───────────────────────────────────────────────────────────────────
if [ -t 1 ]; then
  RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
  CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
else
  RED=''; GREEN=''; YELLOW=''; CYAN=''; BOLD=''; RESET=''
fi

info()    { echo -e "${CYAN}  →${RESET} $*"; }
success() { echo -e "${GREEN}  ✓${RESET} $*"; }
warn()    { echo -e "${YELLOW}  ⚠${RESET} $*"; }
die()     { echo -e "\n${RED}  ✗ ERROR:${RESET} $*\n" >&2; exit 1; }

# ── Banner ────────────────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}╔══════════════════════════════════════════╗${RESET}"
echo -e "${BOLD}║        WakeDesk for Linux                ║${RESET}"
echo -e "${BOLD}║      Remote Access by CyberTech LLC      ║${RESET}"
echo -e "${BOLD}╚══════════════════════════════════════════╝${RESET}"
echo ""

# ── Detect package manager ────────────────────────────────────────────────────
if ! command -v dpkg >/dev/null 2>&1 || ! command -v apt-get >/dev/null 2>&1; then
  die "WakeDesk requires a Debian-based Linux distribution (Raspberry Pi OS, Ubuntu, Kali, Debian).\n  Detected: $(uname -s) — apt/dpkg not found."
fi

# ── Detect architecture ───────────────────────────────────────────────────────
ARCH_RAW="$(uname -m)"
case "$ARCH_RAW" in
  aarch64|arm64) ARCH="arm64" ;;
  x86_64|amd64)  ARCH="amd64" ;;
  armv7l|armhf)  die "32-bit ARM is not supported. Please install 64-bit Raspberry Pi OS." ;;
  *)             die "Unsupported architecture: $ARCH_RAW" ;;
esac

# ── Detect OS ─────────────────────────────────────────────────────────────────
OS_ID=""
OS_NAME=""
OS_VERSION=""
if [ -f /etc/os-release ]; then
  . /etc/os-release
  OS_ID="${ID:-}"
  OS_NAME="${PRETTY_NAME:-${NAME:-unknown}}"
  OS_VERSION="${VERSION_CODENAME:-${VERSION_ID:-}}"
fi

# ── Detect Raspberry Pi ───────────────────────────────────────────────────────
IS_RPI=false
RPI_MODEL=""
if [ -f /proc/device-tree/model ]; then
  RPI_MODEL="$(tr -d '\0' < /proc/device-tree/model 2>/dev/null || true)"
  [[ "$RPI_MODEL" == *"Raspberry Pi"* ]] && IS_RPI=true
fi

# ── Print detected platform ───────────────────────────────────────────────────
info "Detected platform:"
echo "    OS:   $OS_NAME"
echo "    Arch: $ARCH"
if $IS_RPI; then
  echo "    HW:   $RPI_MODEL"
fi
echo ""

# ── Root / sudo setup ─────────────────────────────────────────────────────────
if [[ "$EUID" -eq 0 ]]; then
  SUDO=""
else
  command -v sudo >/dev/null 2>&1 \
    || die "This installer requires root or sudo.\n  Run: sudo bash install_wakedesk.sh"
  SUDO="sudo"
fi

# ── Find the right .deb ───────────────────────────────────────────────────────
# Look for arch-specific deb first (RPi arm64 or amd64), then any deb.
DEB=""
if [[ "$ARCH" == "arm64" ]]; then
  # Prefer the RPi release package, fall back to any arm64 deb
  DEB="$(ls "$SCRIPT_DIR"/WakeDesk-RPi4-RPi5-*-arm64.deb 2>/dev/null | sort -V | tail -1 || true)"
  if [[ -z "$DEB" ]]; then
    DEB="$(ls "$SCRIPT_DIR"/WakeDesk-*arm64*.deb 2>/dev/null | sort -V | tail -1 || true)"
  fi
else
  DEB="$(ls "$SCRIPT_DIR"/WakeDesk-*amd64*.deb 2>/dev/null | sort -V | tail -1 || true)"
  if [[ -z "$DEB" ]]; then
    DEB="$(ls "$SCRIPT_DIR"/WakeDesk-*amd64*.deb "$SCRIPT_DIR"/WakeDesk-*.deb 2>/dev/null | grep -v arm64 | sort -V | tail -1 || true)"
  fi
fi

if [[ -z "$DEB" ]]; then
  echo -e "${RED}  ✗ No matching WakeDesk package found for $ARCH in $SCRIPT_DIR${RESET}" >&2
  echo "" >&2
  echo "  Expected file name patterns:" >&2
  [[ "$ARCH" == "arm64" ]] && echo "    WakeDesk-RPi4-RPi5-X.Y.Z-arm64.deb" >&2
  [[ "$ARCH" == "amd64" ]] && echo "    WakeDesk-X.Y.Z-amd64.deb" >&2
  echo "" >&2
  echo "  Download the full release package (both files) and keep them in the same folder." >&2
  exit 1
fi

success "Found package: $(basename "$DEB")"

# On amd64, the WakeDesk dashboard (wakedesk-host) ships as a separate package.
# On the RPi release, wakedesk-host is already merged into the main .deb.
HOST_DEB=""
if [[ "$ARCH" == "amd64" ]]; then
  HOST_DEB="$(ls "$SCRIPT_DIR"/wakedesk-host_*.deb 2>/dev/null | sort -V | tail -1 || true)"
  if [[ -n "$HOST_DEB" ]]; then
    success "Found package: $(basename "$HOST_DEB")"
  fi
fi

# ── Platform-specific warnings ────────────────────────────────────────────────
if $IS_RPI; then
  if [[ "$ARCH" == "amd64" ]]; then
    die "Raspberry Pi detected but only an amd64 package was found.\n  Download the arm64 RPi package instead."
  fi
  if ! $IS_RPI && [[ "$ARCH" == "arm64" ]] && [[ "$(basename "$DEB")" == *RPi* ]]; then
    warn "RPi package selected on a non-RPi arm64 system. Some RPi-specific features may not work."
  fi
fi

# ── Kali / Ubuntu / Debian notes ─────────────────────────────────────────────
case "$OS_ID" in
  kali)    info "Kali Linux detected — installing WakeDesk desktop client." ;;
  ubuntu)  info "Ubuntu $OS_VERSION detected." ;;
  debian)  info "Debian $OS_VERSION detected." ;;
  raspbian|*) $IS_RPI && info "Raspberry Pi OS detected." || true ;;
esac

# ── Install ───────────────────────────────────────────────────────────────────
echo ""
info "Updating package lists..."
$SUDO apt-get update -qq

echo ""
info "Installing WakeDesk and dependencies (this may take a minute)..."
if [[ -n "$HOST_DEB" ]]; then
  $SUDO apt-get install -y "$DEB" "$HOST_DEB"
else
  $SUDO apt-get install -y "$DEB"
fi

# ── RPi-specific post-install ─────────────────────────────────────────────────
if $IS_RPI; then
  echo ""
  info "Applying Raspberry Pi optimisations..."

  # Ensure sudoers rule is in place (idempotent — postinst already does this,
  # but the Pi may have been set up with a non-standard username).
  DESKTOP_USER="${SUDO_USER:-${USER:-}}"
  if [[ -n "$DESKTOP_USER" && "$DESKTOP_USER" != "root" ]]; then
    SUDOERS_LINE="$DESKTOP_USER ALL=(root) NOPASSWD: /usr/bin/wakedesk-host"
    SUDOERS_FILE=/etc/sudoers.d/wakedesk-host
    if ! grep -qF "$SUDOERS_LINE" "$SUDOERS_FILE" 2>/dev/null; then
      echo "$SUDOERS_LINE" | $SUDO tee -a "$SUDOERS_FILE" >/dev/null
      $SUDO chmod 0440 "$SUDOERS_FILE"
      success "Sudoers rule added for $DESKTOP_USER"
    fi
  fi

  # Install the StatusNotifier tray bridge for LXPanel/LXDE (Raspberry Pi OS default desktop).
  if apt-cache show ayatana-indicator-application >/dev/null 2>&1; then
    info "Installing tray icon bridge for Raspberry Pi OS desktop..."
    $SUDO apt-get install -y ayatana-indicator-application -qq
    success "Tray icon bridge installed"
  fi
fi

# ── Post-install status ───────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}──────────────────────────────────────────${RESET}"
echo -e "${GREEN}${BOLD}  WakeDesk installed successfully!${RESET}"
echo -e "${BOLD}──────────────────────────────────────────${RESET}"
echo ""

if command -v systemctl >/dev/null 2>&1; then
  WD_STATUS="$(systemctl is-active wakedesk.service 2>/dev/null || true)"
  WH_STATUS="$(systemctl is-active wakedesk-host.service 2>/dev/null || true)"
  if [[ "$WH_STATUS" == "active" ]]; then
    success "wakedesk-host.service  — running"
  else
    warn "wakedesk-host: $WH_STATUS"
    warn "Check with: sudo systemctl status wakedesk-host --no-pager"
  fi
  if [[ "$WD_STATUS" == "active" ]]; then
    success "wakedesk.service       — running"
  else
    info "wakedesk.service       — inactive (this is expected before activation)"
    info "It will start automatically once you activate your license."
  fi
fi

echo ""
echo -e "${BOLD}Next steps:${RESET}"
if $IS_RPI; then
  echo "  • Open the desktop app:  Go to Internet → WakeDesk (or run: wakedesk-host-gui)"
  echo "  • The WakeDesk icon will appear in your system tray after next login"
else
  echo "  • Open the desktop app:  wakedesk"
fi
echo "  • Check service status:  sudo systemctl status wakedesk wakedesk-host --no-pager"
echo "  • Activate your license: Open Settings → License in the WakeDesk app"
echo "  • Support:               support@cybertechus.com"
echo ""
