#!/bin/sh
# ChatOSS desktop installer — fetched via `curl -fsSL https://chatoss.ai/install.sh | sh`
#
# Detects the OS and architecture, then downloads the matching asset from the
# latest GitHub release at pagecow/chat-oss-releases.
#
# Environment variables:
#   CHATOSS_INSTALL_DIR  macOS: where to place ChatOSS.app (default /Applications,
#                        falls back to ~/Applications when not writable).
#                        Linux: where to place the AppImage (default ~/.local/bin).

set -e

RELEASES_URL="https://api.github.com/repos/pagecow/chat-oss-releases/releases/latest"
RELEASES_PAGE="https://github.com/pagecow/chat-oss-releases/releases/latest"

OS="$(uname -s)"
ARCH="$(uname -m)"

# Windows shells (Git Bash / MSYS / Cygwin) — point at the PowerShell installer.
case "$OS" in
  MINGW*|MSYS*|CYGWIN*|Windows_NT)
    echo "This is the macOS/Linux installer. On Windows, run this in PowerShell:"
    echo ""
    echo "  irm https://chatoss.ai/install.ps1 | iex"
    exit 1
    ;;
esac

echo "Fetching the latest ChatOSS release…"

RELEASE_JSON="$(curl -fsSL -H "Accept: application/vnd.github+json" "$RELEASES_URL")" || {
  echo "Could not reach the ChatOSS releases API."
  echo "Download manually: $RELEASES_PAGE"
  exit 1
}

# Every asset download URL, one per line, signature files excluded.
ASSET_URLS="$(printf '%s' "$RELEASE_JSON" \
  | grep -o '"browser_download_url"[[:space:]]*:[[:space:]]*"[^"]*"' \
  | grep -o 'https://[^"]*' \
  | grep -v '\.sig$')"

# First asset URL matching a (case-insensitive) pattern, or empty.
find_asset() {
  printf '%s\n' "$ASSET_URLS" | grep -i -e "$1" | head -n 1
}

DOWNLOAD_URL=""

case "$OS" in
  Darwin)
    # ChatOSS ships a UNIVERSAL macOS build (one binary for Apple Silicon +
    # Intel). Both arches prefer the universal DMG first; if a release ever
    # ships arch-specific DMGs instead, fall back to the matching native one.
    case "$ARCH" in
      arm64|aarch64)
        DOWNLOAD_URL="$(find_asset '_universal\.dmg$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '_aarch64\.dmg$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '_x64\.dmg$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '\.dmg$')"
        ;;
      *)
        DOWNLOAD_URL="$(find_asset '_universal\.dmg$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '_x64\.dmg$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '_aarch64\.dmg$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '\.dmg$')"
        ;;
    esac
    ;;
  Linux)
    case "$ARCH" in
      aarch64|arm64)
        DOWNLOAD_URL="$(find_asset '_arm64\.AppImage$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '_aarch64\.AppImage$')"
        if [ -z "$DOWNLOAD_URL" ]; then
          echo "There's no ChatOSS build for Linux $ARCH yet — only x86_64."
          echo "Watch for new releases: $RELEASES_PAGE"
          exit 1
        fi
        ;;
      *)
        DOWNLOAD_URL="$(find_asset '_amd64\.AppImage$')"
        [ -n "$DOWNLOAD_URL" ] || DOWNLOAD_URL="$(find_asset '\.AppImage$')"
        ;;
    esac
    ;;
  *)
    echo "Unsupported OS: $OS. Download manually from $RELEASES_PAGE"
    exit 1
    ;;
esac

if [ -z "$DOWNLOAD_URL" ]; then
  echo "Could not find a ChatOSS release asset for $OS ($ARCH)."
  echo "Download manually: $RELEASES_PAGE"
  exit 1
fi

echo "Downloading $DOWNLOAD_URL …"
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT

case "$OS" in
  Darwin)
    DMG_FILE="$WORK_DIR/chatoss.dmg"
    curl -fsSL -o "$DMG_FILE" "$DOWNLOAD_URL"

    # Pick the install destination: CHATOSS_INSTALL_DIR, else /Applications,
    # else ~/Applications when /Applications isn't writable (non-admin users).
    DEST="${CHATOSS_INSTALL_DIR:-/Applications}"
    if [ ! -d "$DEST" ] || [ ! -w "$DEST" ]; then
      if [ -n "$CHATOSS_INSTALL_DIR" ]; then
        mkdir -p "$DEST"
      else
        DEST="$HOME/Applications"
        mkdir -p "$DEST"
      fi
    fi

    MOUNT_POINT="$WORK_DIR/mnt"
    mkdir -p "$MOUNT_POINT"
    hdiutil attach "$DMG_FILE" -mountpoint "$MOUNT_POINT" -nobrowse -quiet
    APP_PATH="$(find "$MOUNT_POINT" -maxdepth 1 -name '*.app' | head -n 1)"
    if [ -z "$APP_PATH" ]; then
      hdiutil detach "$MOUNT_POINT" -quiet || true
      echo "The downloaded image contained no .app bundle. Download manually: $RELEASES_PAGE"
      exit 1
    fi
    APP_NAME="$(basename "$APP_PATH")"

    # Check the ACTUAL binary architecture (asset names can lie — v0.5.1's
    # "_x64.dmg" contains an arm64 binary). Drives the Rosetta note below,
    # and protects Intel Macs from installing an app that cannot launch.
    MAIN_BIN="$(find "$APP_PATH/Contents/MacOS" -type f -perm +111 2>/dev/null | head -n 1)"
    BIN_INFO="$(file "$MAIN_BIN" 2>/dev/null || true)"
    ROSETTA_NOTE=""
    case "$ARCH" in
      arm64|aarch64)
        if [ -n "$BIN_INFO" ] && ! printf '%s' "$BIN_INFO" | grep -q "arm64"; then
          ROSETTA_NOTE=1
        fi
        ;;
      *)
        if [ -n "$BIN_INFO" ] && ! printf '%s' "$BIN_INFO" | grep -q "x86_64"; then
          hdiutil detach "$MOUNT_POINT" -quiet || true
          echo "This release's macOS build is Apple Silicon-only and won't run on"
          echo "this Intel Mac. Check $RELEASES_PAGE for an Intel build."
          exit 1
        fi
        ;;
    esac

    # Replace (not merge into) any existing install — cp -R into an existing
    # .app would leave stale files from the old version behind.
    rm -rf "$DEST/$APP_NAME"
    cp -R "$APP_PATH" "$DEST/"
    hdiutil detach "$MOUNT_POINT" -quiet
    echo "✓ ChatOSS installed to $DEST/$APP_NAME"

    if [ -n "$ROSETTA_NOTE" ]; then
      echo ""
      echo "Note: this release ships an Intel build; your Apple Silicon Mac runs"
      echo "it through Rosetta 2. If macOS asks to install Rosetta on first"
      echo "launch, accept — or run: softwareupdate --install-rosetta"
    fi
    ;;
  Linux)
    APP_FILE="$WORK_DIR/ChatOSS.AppImage"
    curl -fsSL -o "$APP_FILE" "$DOWNLOAD_URL"
    DEST="${CHATOSS_INSTALL_DIR:-$HOME/.local/bin}"
    mkdir -p "$DEST"
    chmod +x "$APP_FILE"
    mv "$APP_FILE" "$DEST/ChatOSS"
    echo "✓ ChatOSS installed to $DEST/ChatOSS"
    case ":$PATH:" in
      *":$DEST:"*) ;;
      *)
        echo ""
        echo "Note: $DEST isn't on your PATH. Launch with $DEST/ChatOSS,"
        echo "or add it to your PATH."
        ;;
    esac
    ;;
esac

echo ""
echo "Done. Open ChatOSS to get started."
