#!/usr/bin/env bash
set -euo pipefail

ENV_FILE="${SHX_ENV_FILE:-/root/.openclaw/.env}"
if [[ -f "$ENV_FILE" ]]; then
  set -a
  source "$ENV_FILE"
  set +a
fi

usage() {
  cat <<'EOF'
Usage:
  shx-upload <file> [more files...]
  shx-upload --json <file>

Env:
  SHX_URL    Base URL, e.g. https://shx.reversed.dev
  SHX_TOKEN  Zipline API token from the dashboard

Notes:
  - Username/password are only for dashboard login.
  - Uploads use an API token.
EOF
}

want_json=0
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  usage
  exit 0
fi

if [[ "${1:-}" == "--json" ]]; then
  want_json=1
  shift
fi

if [[ $# -lt 1 ]]; then
  usage
  exit 1
fi

: "${SHX_URL:=}"
: "${SHX_TOKEN:=${ZIPLINE_TOKEN:-}}"

if [[ -z "$SHX_URL" ]]; then
  echo "error: SHX_URL is not set" >&2
  exit 1
fi

if [[ -z "$SHX_TOKEN" ]]; then
  cat >&2 <<EOF
error: SHX_TOKEN is not set

Create one in the Zipline dashboard, then add it to $ENV_FILE like:
  SHX_TOKEN=your_token_here
EOF
  exit 1
fi

upload_one() {
  local file="$1"
  if [[ ! -f "$file" ]]; then
    echo "error: file not found: $file" >&2
    return 1
  fi

  local response
  response="$(curl -fsS \
    -H "authorization: $SHX_TOKEN" \
    "$SHX_URL/api/upload" \
    -F "file=@$file")"

  if [[ $want_json -eq 1 ]]; then
    printf '%s\n' "$response"
  else
    if ! command -v jq >/dev/null 2>&1; then
      echo "error: jq is required unless --json is used" >&2
      return 1
    fi
    printf '%s\n' "$response" | jq -r 'if .files then .files[] else . end'
  fi
}

status=0
for file in "$@"; do
  if ! upload_one "$file"; then
    status=1
  fi
done

exit $status
