#!/bin/sh
# Installs Scout 0.1.24 for this user: the app at ~/.local/share/scout/scout, `scout` on the PATH
# and an entry in the app menu. Scout keeps itself up to date from then on. Needs no root.
#   curl -fsSL https://scoutcode.dev/install.sh | sh
set -eu

fail() { echo "scout: $*" >&2; exit 1; }
[ "$(uname -s)" = Linux ] || fail "this installs Scout on Linux. For Windows, see https://scoutcode.dev/#install"
case "$(uname -m)" in
  x86_64 | amd64) platform=linux-x86_64 ;;
  aarch64 | arm64) platform=linux-aarch64 ;;
  *) fail "Scout isn't built for $(uname -m) yet." ;;
esac
url=''
sum=''
case "$platform" in
  linux-x86_64) url='https://xjjziopqclvmrxemqihm.supabase.co/storage/v1/object/public/desktop-releases/linux-x86_64/0.1.24/scout'; sum='55a3d8f52d6296d40964b11bb01f24bf261368d12b18a3cdbfc9baf293a30de9' ;;
  linux-aarch64) url='https://xjjziopqclvmrxemqihm.supabase.co/storage/v1/object/public/desktop-releases/linux-aarch64/0.1.24/scout'; sum='744df8bd38680b39d807f42f3e3cd0ae14c0497e1ef0026b5fd40b6cc3b1705c' ;;
esac
[ -n "$url" ] || fail "there's no Scout for $platform yet. See https://scoutcode.dev/#install"
command -v curl >/dev/null 2>&1 || fail "the installer needs curl."
command -v sha256sum >/dev/null 2>&1 || fail "the installer needs sha256sum (coreutils)."

data="${XDG_DATA_HOME:-$HOME/.local/share}"
dir="$data/scout"
bin="$HOME/.local/bin"
mkdir -p "$dir" "$bin" "$data/applications"

echo "Downloading Scout 0.1.24 for $platform..."
tmp="$dir/.download.$$"
trap 'rm -f "$tmp"' EXIT
curl -fL --progress-bar "$url" -o "$tmp"
echo "$sum  $tmp" | sha256sum -c --status - || fail "the download was damaged, so it wasn't installed. Try again."
chmod 755 "$tmp"
# A rename, so a copy of Scout that's running carries on until it's restarted.
mv -f "$tmp" "$dir/scout"
ln -sf "$dir/scout" "$bin/scout"
curl -fsSL "https://scoutcode.dev/icon.png" -o "$dir/icon.png" 2>/dev/null || true

cat > "$data/applications/scout.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Scout
Comment=A coding agent for your projects
Exec=$dir/scout
Icon=$dir/icon.png
Terminal=false
Categories=Development;
EOF
command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$data/applications" 2>/dev/null || true

echo "Installed Scout to $dir/scout."
missing=$(ldd "$dir/scout" 2>/dev/null | awk '/not found/ { print $1 }' || true)
if [ -n "$missing" ]; then
  echo
  echo "Scout needs some libraries this computer doesn't have yet:" $missing
  echo "  Debian, Ubuntu:  sudo apt install libwebkit2gtk-4.1-0 libxdo3"
  echo "  Fedora:          sudo dnf install webkit2gtk4.1 libxdo"
  echo "  Arch:            sudo pacman -S webkit2gtk-4.1 xdotool"
fi
case ":$PATH:" in
  *":$bin:"*) echo "Start it from your app menu, or run: scout" ;;
  *) echo "Start it from your app menu, or run: $bin/scout ($bin isn't on your PATH)" ;;
esac
