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

# Kluisz Agent Installer
# Usage:
#   curl -fsSL http://<base-url>/install.sh | bash -s -- --agent kluisz-linux-agent --gateway <ip> --ou <uuid>

BASE_URL="https://install.obs.kluisz.cloud"
AGENT="kluisz-agent"
GATEWAY=""
OU=""
API_KEY_ID=""
API_KEY_SECRET=""
INSTALL_DIR="/usr/local/bin"

usage() {
  echo "Usage: $0 --agent <agent> --ou <uuid> --gateway <ip> [--api-key-id <id>] [--api-key-secret <secret>] [--base-url <url>]"
  echo ""
  echo "Agents: kluisz-agent | kluisz-linux-agent | kluisz-node-agent | kluisz-k8s-agent | kluisz-ebpf-agent | kluisz-trivy-agent | kluisz-logging-agent | kluisz-apm-agent"
  exit 1
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --agent)          AGENT="${2:-}";          shift 2 ;;
    --ou)             OU="${2:-}";             shift 2 ;;
    --gateway)        GATEWAY="${2:-}";        shift 2 ;;
    --api-key-id)     API_KEY_ID="${2:-}";     shift 2 ;;
    --api-key-secret) API_KEY_SECRET="${2:-}"; shift 2 ;;
    --base-url)       BASE_URL="${2:-}";       shift 2 ;;
    -h|--help)        usage ;;
    *) echo "Unknown argument: $1"; usage ;;
  esac
done

[ -n "$OU" ] || usage

# Detect OS
case "$(uname)" in
  Linux)  OS="linux"  ;;
  Darwin) OS="darwin" ;;
  *) echo "Unsupported OS: $(uname)"; exit 1 ;;
esac

# Detect architecture
case "$(uname -m)" in
  x86_64)         ARCH="amd64" ;;
  aarch64|arm64)  ARCH="arm64" ;;
  *) echo "Unsupported architecture: $(uname -m)"; exit 1 ;;
esac

BINARY="${AGENT}-${OS}-${ARCH}"
DOWNLOAD_URL="${BASE_URL}/bin/${OS}/${ARCH}/${BINARY}"

echo "Downloading ${AGENT} from ${DOWNLOAD_URL}..."

TMP="$(mktemp)"
curl -fsSL "$DOWNLOAD_URL" -o "$TMP"
chmod +x "$TMP"

if [ "$EUID" -ne 0 ]; then
  sudo mv "$TMP" "${INSTALL_DIR}/${AGENT}"
else
  mv "$TMP" "${INSTALL_DIR}/${AGENT}"
fi

echo "Installed: ${INSTALL_DIR}/${AGENT}"
echo ""

# Build agent args
AGENT_ARGS=("--ou" "$OU")
[ -n "$GATEWAY" ]        && AGENT_ARGS+=("--gateway" "$GATEWAY")
[ -n "$API_KEY_ID" ]     && AGENT_ARGS+=("--api-key-id" "$API_KEY_ID")
[ -n "$API_KEY_SECRET" ] && AGENT_ARGS+=("--api-key-secret" "$API_KEY_SECRET")

echo "Running ${AGENT}..."
if [ "$EUID" -ne 0 ]; then
  sudo "${INSTALL_DIR}/${AGENT}" "${AGENT_ARGS[@]}"
else
  "${INSTALL_DIR}/${AGENT}" "${AGENT_ARGS[@]}"
fi
