#!/bin/sh
# Mystic — Earth Care Network desktop coworker
# Read me: curl -fsSL https://www.earthcare.network/mystic/install.sh
# Run me:  curl -fsSL https://www.earthcare.network/mystic/install.sh | sh
#
# Fetches the latest GitHub Release asset for this machine. If no tagged
# build exists yet, it says so and exits. It never invents a binary.

set -eu

REPO="serenelion/mystic"
LANDING="https://www.earthcare.network/mystic"
MAC_ASSET="Mystic-macos.dmg"
LINUX_ASSET="Mystic-linux.AppImage"

os_hint="darwin"
# Mac/Linux buttons hit /mystic/install/mac and /mystic/install/linux, which
# bake os_hint. curl | sh on /mystic/install.sh uses uname. MYSTIC_OS overrides.

uname_s=$(uname -s 2>/dev/null || echo unknown)
uname_m=$(uname -m 2>/dev/null || echo unknown)

case "${os_hint:-$uname_s}" in
  [Dd]arwin*|macOS|macos|Mac)
    os=darwin
    asset="$MAC_ASSET"
    ;;
  [Ll]inux*|Linux)
    os=linux
    asset="$LINUX_ASSET"
    ;;
  *)
    echo "Mystic installs on Mac and Linux in this first download." >&2
    echo "This machine reports: $uname_s / $uname_m" >&2
    echo "See $LANDING" >&2
    exit 1
    ;;
esac

url="https://github.com/${REPO}/releases/latest/download/$asset"

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

echo "Mystic: fetching $asset for $os ($uname_m)…"

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
dest="$tmpdir/$asset"

http_code=$(curl -fL --progress-bar -o "$dest" -w "%{http_code}" \
  -A "Mystic-installer" \
  "$url" || true)

if [ ! -s "$dest" ] || [ "$http_code" = "404" ] || [ "$http_code" = "000" ]; then
  echo >&2
  echo "Mystic has no published desktop build to install yet." >&2
  echo "The installer is real; GitHub has not tagged a matching Release." >&2
  echo "  Looked for: $url" >&2
  echo "  Releases:   https://github.com/${REPO}/releases" >&2
  echo "  Landing:    $LANDING" >&2
  echo >&2
  exit 2
fi

case "$os" in
  darwin)
    echo "Opening $asset …"
    open "$dest"
    echo "Drag Mystic into Applications when the window appears."
    ;;
  linux)
    chmod +x "$dest"
    target="$HOME/.local/bin"
    mkdir -p "$target"
    out="$target/mystic"
    mv "$dest" "$out"
    echo "Installed to $out"
    echo "Add $target to PATH if it is not already there, then run: mystic"
    ;;
esac

echo "Done. Activate the enterprise at $LANDING when you are ready to be found."
