#!/bin/sh
# kimi-ops installer
#
#   curl -fsSL https://lumbot.technology/install.sh | sh -s YOUR-LICENCE-KEY
#
# Read this before you run it. It downloads one zip, unpacks it into
# ./kimi-ops, and writes your licence into that folder. Nothing else.

set -eu

KEY="${1:-${LICENCE_KEY:-}}"
BASE="https://lumbot.technology"
DIR="${KIMI_OPS_DIR:-kimi-ops}"

red()  { printf '\033[31m%s\033[0m\n' "$1"; }
dim()  { printf '\033[2m%s\033[0m\n' "$1"; }
bold() { printf '\033[1m%s\033[0m\n' "$1"; }

if [ -z "$KEY" ]; then
  red "No licence key given."
  echo
  echo "  curl -fsSL $BASE/install.sh | sh -s LMB-XXXX-XXXX-XXXX-XXXX"
  echo
  echo "Claim one at $BASE"
  exit 1
fi

case "$KEY" in
  LMB-????-????-????-????) ;;
  *) red "That does not look like a licence key (expected LMB-XXXX-XXXX-XXXX-XXXX)."; exit 1 ;;
esac

if [ -e "$DIR" ]; then
  red "$DIR already exists here. Move it aside, or set KIMI_OPS_DIR to another name."
  exit 1
fi

command -v curl >/dev/null 2>&1 || { red "curl is required."; exit 1; }
command -v unzip >/dev/null 2>&1 || { red "unzip is required."; exit 1; }

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT INT TERM

bold "Downloading kimi-ops..."
HTTP=$(curl -fsSL -w '%{http_code}' -o "$TMP/kimi-ops.zip" "$BASE/api/download?key=$KEY" || true)

if [ ! -s "$TMP/kimi-ops.zip" ]; then
  red "Download failed (HTTP ${HTTP:-no response})."
  echo "If the key is right, the gate may not recognise it yet — claim again at $BASE"
  exit 1
fi

unzip -q "$TMP/kimi-ops.zip" -d "$TMP/out"
[ -d "$TMP/out/kimi-ops" ] || { red "The archive was not what we expected."; exit 1; }

mv "$TMP/out/kimi-ops" "$DIR"
printf '%s\n' "$KEY" > "$DIR/.licence"

echo
bold "Installed into ./$DIR"
dim  "licence $KEY"
echo
echo "Next:"
echo "  cd $DIR"
echo "  cp .env.example .env      # then add your own Kimi API key"
echo "  npm start"
echo
dim "No npm install needed — this project has zero dependencies."
