#!/bin/sh
# SuperMirror for Linux — installer for the release tarball.
#
#   curl -fsSL https://supermirror.app/linux/install.sh | sh
#
# Puts `supermirror` in ~/.local/bin, installs the systemd user service and
# the desktop entry, and starts the daemon. Nothing needs root except the
# adb/udev packages, which it tells you about rather than installing.
set -eu

VERSION="${SUPERMIRROR_VERSION:-latest}"
BASE="${SUPERMIRROR_BASE_URL:-https://supermirror.app}"
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|aarch64) ;;
  *) echo "unsupported architecture: $ARCH" >&2; exit 1 ;;
esac

if [ "$VERSION" = "latest" ]; then
  URL="$BASE/supermirror-linux-$ARCH.tar.gz"
else
  URL="$BASE/updates/SuperMirror-v$VERSION-linux-$ARCH.tar.gz"
fi

BIN_DIR="${HOME}/.local/bin"
UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
APP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

echo "downloading $URL"
curl -fsSL "$URL" -o "$TMP/supermirror.tar.gz"
tar -xzf "$TMP/supermirror.tar.gz" -C "$TMP"

mkdir -p "$BIN_DIR"
install -m755 "$TMP"/supermirror-linux-*/supermirror "$BIN_DIR/supermirror"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) echo "note: add $BIN_DIR to your PATH to run 'supermirror' from a terminal" ;;
esac

if ! command -v adb >/dev/null 2>&1; then
  echo
  echo "adb is not installed. Install it with your package manager:"
  echo "  Arch / Omarchy:   sudo pacman -S android-tools android-udev"
  echo "  Debian / Ubuntu:  sudo apt install adb android-sdk-platform-tools-common"
  echo "  Fedora:           sudo dnf install android-tools"
fi

# One command wires up the launcher entry, icon, and autostart service.
"$BIN_DIR/supermirror" setup || echo "run '$BIN_DIR/supermirror setup' to finish setup"

echo
echo "Done. Enable USB debugging on your tablet, plug it in, and tap Allow."
echo "SuperMirror is now in your app launcher. Run 'supermirror doctor' if nothing happens."
