#!/usr/bin/env bash
#
# Install or uninstall realm.
#
# Usage:
#   curl -fsSL https://realm.rs/install.sh | bash
#   curl -fsSL https://realm.rs/install.sh | bash -s -- --version 0.0.1
#   curl -fsSL https://realm.rs/install.sh | bash -s -- --uninstall
#
# Installs binary to ~/.local/bin.
# Installs data to the platform data directory:
#   Linux:  ~/.local/share/realm/data
#   macOS:  ~/Library/Application Support/realm/data

set -euo pipefail

BIN_DIR="${REALM_BIN_DIR:-$HOME/.local/bin}"
OS="$(uname -s)"

case "$OS" in
    Linux)
        DATA_PARENT="${REALM_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/realm}"
        ;;
    Darwin)
        DATA_PARENT="${REALM_DATA_DIR:-$HOME/Library/Application Support/realm}"
        ;;
    *)
        echo "Unsupported OS: $OS"; exit 1
        ;;
esac

DATA_DIR="$DATA_PARENT/data"

# --- Uninstall ---

if [ "${1:-}" = "--uninstall" ]; then
    echo "Uninstalling realm..."

    if [ -f "$BIN_DIR/realm" ]; then
        rm "$BIN_DIR/realm"
        echo "Removed $BIN_DIR/realm"
    else
        echo "Binary not found at $BIN_DIR/realm"
    fi

    if [ -d "$DATA_PARENT" ]; then
        rm -rf "$DATA_PARENT"
        echo "Removed $DATA_PARENT"
    else
        echo "Data directory not found at $DATA_PARENT"
    fi

    echo "Done."
    exit 0
fi

# --- Install ---

VERSION="${1:-latest}"
BASE_URL="https://realm.rs/releases"
ARCH="$(uname -m)"

case "$ARCH" in
    x86_64)        ARCH="x86_64" ;;
    aarch64|arm64) ARCH="aarch64" ;;
    *)             echo "Unsupported architecture: $ARCH"; exit 1 ;;
esac

case "$OS" in
    Linux)  PLATFORM="unknown-linux-gnu" ;;
    Darwin) PLATFORM="apple-darwin" ;;
esac

TARGET="${ARCH}-${PLATFORM}"
ARCHIVE="realm-${VERSION}-${TARGET}.tar.gz"
URL="${BASE_URL}/${VERSION}/${ARCHIVE}"

echo "Downloading realm ${VERSION} for ${TARGET}..."

TMPDIR="$(mktemp -d)"
trap 'rm -rf "$TMPDIR"' EXIT

curl -fSL "$URL" -o "$TMPDIR/$ARCHIVE"
tar xzf "$TMPDIR/$ARCHIVE" -C "$TMPDIR"

EXTRACTED="$(find "$TMPDIR" -maxdepth 1 -type d -name 'realm-*' | head -1)"

# Install binary
mkdir -p "$BIN_DIR"
cp "$EXTRACTED/realm" "$BIN_DIR/realm"
chmod +x "$BIN_DIR/realm"

# Remove macOS quarantine attribute
if [ "$OS" = "Darwin" ]; then
    xattr -dr com.apple.quarantine "$BIN_DIR/realm" 2>/dev/null || true
fi

# Install data
mkdir -p "$DATA_DIR"
cp -r "$EXTRACTED/data/"* "$DATA_DIR/"

echo ""
echo "Installed realm to $BIN_DIR/realm"
echo "Installed data to $DATA_DIR"
echo ""
echo "Make sure $BIN_DIR is in your PATH."
