#!/bin/sh
# Instachat CLI by SoulfulAI. Versioned download; never requests sudo.
set -eu

install_instachat() {
  for tool in node npm curl; do
    command -v "$tool" >/dev/null 2>&1 || {
      printf '%s\n' "Instachat requires $tool. Install Node.js 22 or newer (with npm) and curl, then retry." >&2
      return 1
    }
  done
  node -e 'if (Number(process.versions.node.split(".")[0]) < 22) process.exit(1)' || {
    printf '%s\n' 'Instachat requires Node.js 22 or newer.' >&2
    return 1
  }
  case "$(uname -s)" in
    Darwin|Linux) ;;
    *) printf '%s\n' 'This installer supports macOS and Linux shells.' >&2; return 1 ;;
  esac

  instachat_tmp=$(mktemp -d "${TMPDIR:-/tmp}/instachat-install.XXXXXXXX")
  trap 'rm -rf "$instachat_tmp"' EXIT
  trap 'exit 1' HUP INT TERM
  instachat_package="$instachat_tmp/instachat-1.3.2.tgz"
  printf '%s\n' 'Downloading Instachat 1.3.2…'
  curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \
    --connect-timeout 20 --max-time 300 \
    'https://github.com/soulful-ai/instachat-releases/releases/download/v1.3.2/soulful-ai-instachat-1.3.2.tgz' -o "$instachat_package"
  node --input-type=module - "$instachat_package" <<'VERIFY'
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
const bytes = readFileSync(process.argv[2]);
const expected = '7f6c4a6d9d10b3fa34bf140ad13019b5a03cd2123828952ba3e1baab1d9cf7d8';
if (bytes.length !== 9139021 || createHash('sha256').update(bytes).digest('hex') !== expected) {
  console.error('Instachat download failed integrity verification. Nothing was installed.');
  process.exit(1);
}
VERIFY
  npm install --global "$instachat_package" || {
    printf '%s\n' 'Installation failed. Check that your npm global prefix is writable, then retry.' >&2
    return 1
  }
  instachat_prefix=$(npm prefix --global)
  "$instachat_prefix/bin/instachat" --version
  case ":$PATH:" in
    *":$instachat_prefix/bin:"*) ;;
    *) printf '%s\n' "Add $instachat_prefix/bin to your PATH before running Instachat." ;;
  esac
  printf '\n%s\n' 'Next: instachat login' 'Sign in at web.instachat.cc when the browser opens.'
}

install_instachat
