#!/usr/bin/env bash
# CodeNeo installer — hosted at https://codeneo.cn/releases/install.sh
set -euo pipefail

BASE="${CODENEO_RELEASE_BASE:-https://codeneo.cn/releases}"
CONTACT="contact@codeneo.cn"

echo "CodeNeo installer"
echo "  mirror: $BASE"
echo

os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
  Linux)
    pkg=""
    case "$arch" in
      x86_64|amd64) pkg="codeneo-linux-amd64.deb" ;;
      aarch64|arm64) pkg="codeneo-linux-arm64.deb" ;;
      *)
        echo "Unsupported Linux arch: $arch" >&2
        echo "Write $CONTACT with your platform to get a package." >&2
        exit 1
        ;;
    esac
    url="$BASE/$pkg"
    tmpdir="$(mktemp -d)"
    tmp="$tmpdir/$pkg"
    echo "Downloading $url"
    if ! curl -fsSL "$url" -o "$tmp"; then
      echo "Package is not published on this mirror yet." >&2
      echo "Write $CONTACT (include Ubuntu version and $arch) to receive a .deb." >&2
      rm -rf "$tmpdir"
      exit 1
    fi
    # Optional integrity check: verify against a checksum file published next to the
    # package. No checksum published yet -> warn and continue; mismatch -> abort.
    if curl -fsSL "$BASE/SHA256SUMS" -o "$tmpdir/SHA256SUMS" 2>/dev/null && grep -qE "[[:space:]]${pkg}\$" "$tmpdir/SHA256SUMS"; then
      (cd "$tmpdir" && grep -E "[[:space:]]${pkg}\$" SHA256SUMS | sha256sum -c -)
    elif curl -fsSL "${url}.sha256" -o "$tmpdir/${pkg}.sha256" 2>/dev/null; then
      hash="$(awk '{print $1}' "$tmpdir/${pkg}.sha256")"
      (cd "$tmpdir" && printf '%s  %s\n' "$hash" "$pkg" | sha256sum -c -)
    else
      echo "Warning: no checksum published for $pkg; skipping integrity check." >&2
    fi
    echo "Installing $pkg (requires sudo)"
    sudo dpkg -i "$tmp" || sudo apt-get install -f -y
    rm -rf "$tmpdir"
    echo "Done. Try: codeneo --version"
    ;;
  Darwin|MINGW*|MSYS*|CYGWIN*)
    echo "Desktop installers for Windows / macOS are not piped through this script."
    echo "Write $CONTACT with your OS to receive an installer, or use the download page:"
    echo "  https://codeneo.cn/download.html"
    exit 1
    ;;
  *)
    echo "Unsupported OS: $os" >&2
    echo "Write $CONTACT for a supported installer." >&2
    exit 1
    ;;
esac
