#!/bin/sh
# Install Caesar, the campaign operations terminal client.
# Usage:
#   curl -fsSL https://app.caesar.xyz/install.sh | sh
#   curl -fsSL https://app.caesar.xyz/install.sh | sh -s -- [VERSION] [--no-modify-path]
# Production installs the command caesar; staging installs caesar-staging beside it.
set -eu

BASE_URL="${CAESAR_BASE_URL:-https://app.caesar.xyz}"
NAME="caesar"
TARGET="${CAESAR_VERSION:-latest}"
NO_MODIFY_PATH=""

while [ "$#" -gt 0 ]; do
  case "$1" in
    --no-modify-path)
      NO_MODIFY_PATH=1
      shift
      ;;
    -h|--help)
      cat <<'EOF'
Caesar installer

Usage:
  curl -fsSL https://app.caesar.xyz/install.sh | sh
  curl -fsSL https://app.caesar.xyz/install.sh | sh -s -- [VERSION] [--no-modify-path]

Options:
  VERSION            Install a specific version (e.g. 1.0.0) instead of latest
  --no-modify-path   Do not add ~/.local/bin to your shell profile
  -h, --help         Show this help
EOF
      exit 0
      ;;
    -*)
      printf 'Unknown option: %s\n' "$1" >&2
      exit 2
      ;;
    *)
      TARGET="$1"
      shift
      ;;
  esac
done

TARGET="${TARGET#v}"
TARGET="${TARGET#caesar-v}"

if [ "$TARGET" != "latest" ] && ! printf '%s\n' "$TARGET" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
  printf 'Invalid Caesar version: %s\n' "$TARGET" >&2
  exit 2
fi

if [ "$(id -u)" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != "root" ] && [ -z "${CAESAR_ALLOW_SUDO:-}" ]; then
  cat >&2 <<EOF
Error: do not run this installer with sudo.

Caesar installs under your home directory (~/.local/share/${NAME} and ~/.local/bin/${NAME})
and does not need root privileges. Re-run without sudo:

    curl -fsSL ${BASE_URL}/install.sh | sh

To intentionally install for root, set CAESAR_ALLOW_SUDO=1.
EOF
  exit 1
fi

case "$(uname -s)" in
  Darwin) os="darwin" ;;
  Linux) os="linux" ;;
  *)
    printf 'Unsupported operating system: %s (Caesar supports macOS and Linux).\n' "$(uname -s)" >&2
    exit 1
    ;;
esac

case "$(uname -m)" in
  x86_64|amd64) arch="x64" ;;
  arm64|aarch64) arch="arm64" ;;
  *)
    printf 'Unsupported architecture: %s (Caesar supports arm64 and x64).\n' "$(uname -m)" >&2
    exit 1
    ;;
esac

# Prefer native arm64 on Apple Silicon Macs even when invoked from a Rosetta shell.
if [ "$os" = "darwin" ] && [ "$arch" = "x64" ]; then
  if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = "1" ]; then
    arch="arm64"
  fi
fi

platform="${os}-${arch}"

if command -v curl >/dev/null 2>&1; then
  downloader="curl"
elif command -v wget >/dev/null 2>&1; then
  downloader="wget"
else
  printf 'Either curl or wget is required to install Caesar.\n' >&2
  exit 1
fi

if ! command -v tar >/dev/null 2>&1; then
  printf 'tar is required to install Caesar.\n' >&2
  exit 1
fi

download() {
  url="$1"
  out="${2:-}"
  if [ "$downloader" = "curl" ]; then
    if [ -n "$out" ]; then
      curl -fsSL --retry 2 -o "$out" "$url"
    else
      curl -fsSL --retry 2 "$url"
    fi
  else
    if [ -n "$out" ]; then
      wget -q -O "$out" "$url"
    else
      wget -q -O - "$url"
    fi
  fi
}

sha256_file() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    printf 'shasum or sha256sum is required to verify the Caesar download.\n' >&2
    return 1
  fi
}

extract_field() {
  json="$1"
  plat="$2"
  key="$3"
  if command -v jq >/dev/null 2>&1; then
    printf '%s\n' "$json" | jq -r --arg p "$plat" --arg k "$key" '.platforms[$p][$k] // empty'
    return 0
  fi
  printf '%s\n' "$json" | tr -d '\r\n' | awk -v plat="\"$plat\"" -v key="\"$key\"" '
  {
    idx = index($0, plat)
    if (idx == 0) exit 1
    rest = substr($0, idx + length(plat))
    brace = index(rest, "{")
    if (brace == 0) exit 1
    rest = substr(rest, brace + 1)
    closeb = index(rest, "}")
    if (closeb == 0) exit 1
    obj = substr(rest, 1, closeb - 1)
    kidx = index(obj, key)
    if (kidx == 0) exit 1
    val = substr(obj, kidx + length(key))
    sub(/^[[:space:]]*:[[:space:]]*/, "", val)
    if (substr(val, 1, 1) == "\"") {
      val = substr(val, 2)
      q = index(val, "\"")
      if (q == 0) exit 1
      print substr(val, 1, q - 1)
    } else {
      sub(/[^0-9].*$/, "", val)
      print val
    }
  }'
}

BASE_URL="${BASE_URL%/}"

if [ "$TARGET" = "latest" ]; then
  version="$(download "${BASE_URL}/releases/latest" | tr -d '\r\n[:space:]')"
else
  version="$TARGET"
fi

if ! printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
  printf 'Failed to resolve a valid Caesar release version from %s.\n' "$BASE_URL" >&2
  exit 1
fi

manifest="$(download "${BASE_URL}/releases/${version}/manifest.json")"
file="$(extract_field "$manifest" "$platform" "file" || true)"
expected_sha="$(extract_field "$manifest" "$platform" "sha256" || true)"
expected_size="$(extract_field "$manifest" "$platform" "size" || true)"

if [ -z "$file" ] || [ -z "$expected_sha" ]; then
  printf 'Caesar %s is not available for %s.\n' "$version" "$platform" >&2
  exit 1
fi

if ! printf '%s\n' "$expected_sha" | grep -Eq '^[0-9a-f]{64}$'; then
  printf 'Invalid SHA-256 checksum in release manifest.\n' >&2
  exit 1
fi

tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/caesar-install.XXXXXX")"
cleanup() {
  rm -rf "$tmp_dir"
}
trap cleanup EXIT INT TERM

archive="${tmp_dir}/${file}"
printf 'Downloading Caesar %s (%s)...\n' "$version" "$platform"
download "${BASE_URL}/releases/${version}/${file}" "$archive"

actual_sha="$(sha256_file "$archive")"
if [ "$actual_sha" != "$expected_sha" ]; then
  printf 'Checksum mismatch for %s (expected %s, got %s).\n' "$file" "$expected_sha" "$actual_sha" >&2
  exit 1
fi

if [ -n "$expected_size" ] && printf '%s\n' "$expected_size" | grep -Eq '^[1-9][0-9]*$'; then
  actual_size="$(wc -c < "$archive" | tr -d '[:space:]')"
  if [ "$actual_size" != "$expected_size" ]; then
    printf 'Size mismatch for %s (expected %s bytes, got %s bytes).\n' "$file" "$expected_size" "$actual_size" >&2
    exit 1
  fi
fi

stage="${tmp_dir}/unpacked"
mkdir -p "$stage"
tar -xzf "$archive" -C "$stage"

if [ ! -f "${stage}/caesar" ]; then
  printf 'Release archive %s did not contain the caesar binary.\n' "$file" >&2
  exit 1
fi
chmod 755 "${stage}/caesar"

set -- --from "$stage" --server "$BASE_URL"
if [ "$NAME" != "caesar" ]; then
  set -- "$@" --name "$NAME"
fi
if [ -n "$NO_MODIFY_PATH" ]; then
  set -- "$@" --no-modify-path
fi
"${stage}/caesar" install "$@"
