#!/bin/sh
set -eu

VERSION=0.1.0
ORIGIN=https://img.zulanhongdan.net
AGENT=
if [ "$#" -gt 0 ]; then
  if [ "$#" -ne 2 ] || [ "$1" != '--agent' ]; then
    echo 'Usage: sh install.sh [--agent codex|claude|cursor|workbuddy|doubao|universal]' >&2
    exit 2
  fi
  AGENT=$2
  case "$AGENT" in codex|claude|claude-code|cursor|workbuddy|codebuddy|doubao|universal|all) ;; *) echo 'Unsupported agent' >&2; exit 2 ;; esac
fi
command -v node >/dev/null 2>&1 || { echo 'Node.js 22+ is required: https://nodejs.org/' >&2; exit 1; }
command -v npm >/dev/null 2>&1 || { echo 'npm is required.' >&2; exit 1; }
node -e 'if(Number(process.versions.node.split(".")[0])<22)process.exit(1)' || { echo 'Please upgrade to Node.js 22 or newer.' >&2; exit 1; }
command -v curl >/dev/null 2>&1 || { echo 'curl is required.' >&2; exit 1; }
TASK_DIR=$(mktemp -d)
trap 'rm -rf "$TASK_DIR"' EXIT HUP INT TERM
PACKAGE=gpt-image-$VERSION.tgz
curl --proto '=https' --tlsv1.2 -fsSL "$ORIGIN/downloads/$PACKAGE" -o "$TASK_DIR/$PACKAGE"
curl --proto '=https' --tlsv1.2 -fsSL "$ORIGIN/downloads/SHA256SUMS" -o "$TASK_DIR/SHA256SUMS"
EXPECTED=$(awk -v filename="$PACKAGE" '$2 == filename {print $1}' "$TASK_DIR/SHA256SUMS")
[ "${#EXPECTED}" -eq 64 ] || { echo 'Checksum entry missing.' >&2; exit 1; }
if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL=$(sha256sum "$TASK_DIR/$PACKAGE" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
  ACTUAL=$(shasum -a 256 "$TASK_DIR/$PACKAGE" | awk '{print $1}')
else
  echo 'sha256sum or shasum is required.' >&2; exit 1
fi
[ "$ACTUAL" = "$EXPECTED" ] || { echo 'Checksum mismatch; installation cancelled.' >&2; exit 1; }
INSTALL_PREFIX=${GPT_IMAGE_INSTALL_PREFIX:-"$HOME/.local"}
npm install --global --ignore-scripts --prefix "$INSTALL_PREFIX" "$TASK_DIR/$PACKAGE"
CLI="$INSTALL_PREFIX/bin/gpt-image"
"$CLI" version
if [ -n "$AGENT" ]; then "$CLI" setup --agent "$AGENT"; fi
case ":$PATH:" in *":$INSTALL_PREFIX/bin:"*) ;; *)
  printf '\nAdd this directory to PATH in your shell profile:\n%s/bin\n' "$INSTALL_PREFIX"
  ;;
esac
printf '\nNext: gpt-image configure\nThen: gpt-image setup --agent codex\n'
