#!/usr/bin/env bash
# ============================================================================
# Grain one-click Linux installer (Ubuntu / Debian)
# ============================================================================
# Usage:
#   curl -fsSL https://download.grain.sh/install-linux.sh | bash
#
# Downloads the latest .deb and installs with apt (handles deps).
# Falls back to dpkg if apt is unavailable.
# ============================================================================
set -euo pipefail

BASE="${GRAIN_DOWNLOAD_BASE:-https://download.grain.sh}"
DEB_URL="${BASE}/Grain-latest-linux-amd64.deb"
TMP="${TMPDIR:-/tmp}/Grain-latest-linux-amd64.deb"

echo "════════════════════════════════════════"
echo "  Grain desktop — one-click Linux install"
echo "════════════════════════════════════════"
echo "  Downloading: ${DEB_URL}"
echo

if ! command -v curl >/dev/null 2>&1; then
  echo "✗ curl is required" >&2
  exit 1
fi

curl -fsSL -o "$TMP" "$DEB_URL"
SIZE=$(wc -c <"$TMP" | tr -d ' ')
echo "  Saved ${SIZE} bytes → ${TMP}"

if command -v apt-get >/dev/null 2>&1; then
  echo "  Installing with apt (you may be prompted for your password)…"
  sudo apt-get install -y "$TMP"
elif command -v dpkg >/dev/null 2>&1; then
  echo "  Installing with dpkg…"
  sudo dpkg -i "$TMP" || sudo apt-get -f install -y
else
  echo "✗ Neither apt-get nor dpkg found. Extract manually or use the AppImage:" >&2
  echo "    ${BASE}/Grain-latest-linux-x86_64.AppImage" >&2
  exit 1
fi

rm -f "$TMP" 2>/dev/null || true

echo
echo "✓ Grain installed."
echo "  Launch: grain"
echo "  Or open “Grain” from your app menu."
echo
if command -v grain >/dev/null 2>&1; then
  grain --version 2>/dev/null || true
fi
